doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
20ea7b28-68d3-4f41-a057-1cd90d937952
{ "language": "C#" }
```c# #load "LogHelper.csx" #load "FunctionNameHelper.csx" using System.Configuration; public static class AppSettingsHelper { public static string GetAppSetting(string SettingName, bool LogValue = true ) { string SettingValue = ""; string methodName = this.GetType().FullName; try { SettingValue = ConfigurationManager.AppSettings[SettingName].ToString(); if ((!String.IsNullOrEmpty(SettingValue)) && LogValue) { LogHelper.Info($"{FunctionnameHelper} {GetFunctionName()} {methodName} Retreived AppSetting {SettingName} with a value of {SettingValue}"); } else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue) { LogHelper.Info($"{FunctionnameHelper} {methodName} Retreived AppSetting {SettingName} but logging value was turned off"); } else if(!String.IsNullOrEmpty(SettingValue)) { LogHelper.Info($"{FunctionnameHelper} {methodName} AppSetting {SettingName} was null or empty"); } } catch (ConfigurationErrorsException ex) { LogHelper.Error($"{FunctionnameHelper} {methodName} Unable to find AppSetting {SettingName} with exception of {ex.Message}"); } catch (System.Exception ex) { LogHelper.Error($"{FunctionnameHelper} {methodName} Looking for AppSetting {SettingName} caused an exception of {ex.Message}"); } return SettingValue; } }``` Use the correct call to FunctionNameHelper
```c# #load "LogHelper.csx" #load "FunctionNameHelper.csx" using System.Configuration; public static class AppSettingsHelper { public static string GetAppSetting(string SettingName, bool LogValue = true ) { string SettingValue = ""; string methodName = this.GetType().FullName; try { SettingValue = ConfigurationManager.AppSettings[SettingName].ToString(); if ((!String.IsNullOrEmpty(SettingValue)) && LogValue) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {GetFunctionName()} {methodName} Retreived AppSetting {SettingName} with a value of {SettingValue}"); } else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {methodName} Retreived AppSetting {SettingName} but logging value was turned off"); } else if(!String.IsNullOrEmpty(SettingValue)) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {methodName} AppSetting {SettingName} was null or empty"); } } catch (ConfigurationErrorsException ex) { LogHelper.Error($"{FunctionnameHelper.GetFunctionName()} {methodName} Unable to find AppSetting {SettingName} with exception of {ex.Message}"); } catch (System.Exception ex) { LogHelper.Error($"{FunctionnameHelper.GetFunctionName()} {methodName} Looking for AppSetting {SettingName} caused an exception of {ex.Message}"); } return SettingValue; } }```
85cec91c-f18b-41ba-b62e-5bedab21a828
{ "language": "C#" }
```c# namespace PKHeX.WinForms { partial class Main { public System.Windows.Forms.ToolStripMenuItem EnableAutoLegality(System.ComponentModel.ComponentResourceManager resources) { this.Menu_ShowdownImportPKMModded = new System.Windows.Forms.ToolStripMenuItem(); this.Menu_ShowdownImportPKMModded.Image = ((System.Drawing.Image)(resources.GetObject("Menu_ShowdownImportPKM.Image"))); this.Menu_ShowdownImportPKMModded.Name = "Menu_ShowdownImportPKMModded"; this.Menu_ShowdownImportPKMModded.Size = new System.Drawing.Size(231, 22); this.Menu_ShowdownImportPKMModded.Text = "Modded Showdown Import"; this.Menu_ShowdownImportPKMModded.Click += new System.EventHandler(this.ClickShowdownImportPKMModded); return this.Menu_ShowdownImportPKMModded; } private System.Windows.Forms.ToolStripMenuItem Menu_ShowdownImportPKMModded; } }``` Change aliasing of Modded Showdown Import
```c# namespace PKHeX.WinForms { partial class Main { public System.Windows.Forms.ToolStripMenuItem EnableAutoLegality(System.ComponentModel.ComponentResourceManager resources) { this.Menu_ShowdownImportPKMModded = new System.Windows.Forms.ToolStripMenuItem(); this.Menu_ShowdownImportPKMModded.Image = ((System.Drawing.Image)(resources.GetObject("Menu_ShowdownImportPKM.Image"))); this.Menu_ShowdownImportPKMModded.Name = "Menu_ShowdownImportPKMModded"; this.Menu_ShowdownImportPKMModded.Size = new System.Drawing.Size(231, 22); this.Menu_ShowdownImportPKMModded.Text = "Import with Auto-Legality Mod"; this.Menu_ShowdownImportPKMModded.Click += new System.EventHandler(this.ClickShowdownImportPKMModded); return this.Menu_ShowdownImportPKMModded; } private System.Windows.Forms.ToolStripMenuItem Menu_ShowdownImportPKMModded; } } ```
f1a948e3-2312-4135-9602-77206a169349
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using NuGet.Test.Helpers; using Sleet.Test.Common; namespace Sleet.AmazonS3.Tests { public class AmazonS3FileSystemTests { [EnvVarExistsFact(AmazonS3TestContext.EnvAccessKeyId)] public async Task GivenAS3AccountVerifyBucketOperations() { using (var testContext = new AmazonS3TestContext()) { testContext.CreateBucketOnInit = false; await testContext.InitAsync(); // Verify at the start (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse(); // Create await testContext.FileSystem.CreateBucket(testContext.Logger, CancellationToken.None); (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeTrue(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeTrue(); // Delete await testContext.FileSystem.DeleteBucket(testContext.Logger, CancellationToken.None); (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse(); await testContext.CleanupAsync(); } } } }``` Fix S3 create bucket test
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using NuGet.Test.Helpers; using Sleet.Test.Common; namespace Sleet.AmazonS3.Tests { public class AmazonS3FileSystemTests { [EnvVarExistsFact(AmazonS3TestContext.EnvAccessKeyId)] public async Task GivenAS3AccountVerifyBucketOperations() { using (var testContext = new AmazonS3TestContext()) { testContext.CreateBucketOnInit = false; await testContext.InitAsync(); // Verify at the start (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse(); // Create await testContext.FileSystem.CreateBucket(testContext.Logger, CancellationToken.None); (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeTrue(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeTrue(); await testContext.CleanupAsync(); } } } }```
3ab987f3-79f1-4c0d-9342-fb2af0fe2957
{ "language": "C#" }
```c# using NGM.Forum.Models; namespace NGM.Forum.ViewModels { public class PostBodyEditorViewModel { public PostPart PostPart { get; set; } public string Text { get { return PostPart.Record.Text; } set { PostPart.Record.Text = value; } } public string Format { get { return PostPart.Record.Format; } set { PostPart.Record.Format = value; } } public string EditorFlavor { get; set; } } }``` Trim end of post on Save. Incase someone hits enter loads and then blows the size of the page. This will stop that.
```c# using NGM.Forum.Models; namespace NGM.Forum.ViewModels { public class PostBodyEditorViewModel { public PostPart PostPart { get; set; } public string Text { get { return PostPart.Record.Text; } set { PostPart.Record.Text = string.IsNullOrWhiteSpace(value) ? value : value.TrimEnd(); } } public string Format { get { return PostPart.Record.Format; } set { PostPart.Record.Format = value; } } public string EditorFlavor { get; set; } } }```
197de137-750a-46d1-a8a4-3cd604719c56
{ "language": "C#" }
```c# using System; using System.Web; namespace Umbraco.Web { internal class AspNetHttpContextAccessor : IHttpContextAccessor { public HttpContextBase HttpContext { get { return new HttpContextWrapper(System.Web.HttpContext.Current); } set { throw new NotSupportedException(); } } } } ``` Fix if httpContext is null we cannot wrap it
```c# using System; using System.Web; namespace Umbraco.Web { internal class AspNetHttpContextAccessor : IHttpContextAccessor { public HttpContextBase HttpContext { get { var httpContext = System.Web.HttpContext.Current; return httpContext is null ? null : new HttpContextWrapper(httpContext); } set { throw new NotSupportedException(); } } } } ```
96449b09-8e8c-47a5-a3a2-b9a2a389f13f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace ADWS.Models { [DataContract] public class UserInfoResponse { [DataMember] public string Title { set; get; } [DataMember] public string DisplayName { set; get; } [DataMember] public string FirstName { set; get; } [DataMember] public string LastName { set; get; } [DataMember] public string SamAccountName { set; get; } [DataMember] public string Upn { set; get; } [DataMember] public string EmailAddress { set; get; } [DataMember] public string EmployeeId { set; get; } [DataMember] public string Department { set; get; } [DataMember] public string BusinessPhone { get; set; } [DataMember] public string Telephone { get; set; } [DataMember] public string SipAccount { set; get; } [DataMember] public string PrimaryHomeServerDn { get; set; } [DataMember] public string PoolName { set; get; } [DataMember] public string PhysicalDeliveryOfficeName { set; get; } [DataMember] public string OtherTelphone { get; set; } } }``` Add message inside this class to convey exception
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace ADWS.Models { [DataContract] public class UserInfoResponse { [DataMember] public string Title { set; get; } [DataMember] public string DisplayName { set; get; } [DataMember] public string FirstName { set; get; } [DataMember] public string LastName { set; get; } [DataMember] public string SamAccountName { set; get; } [DataMember] public string Upn { set; get; } [DataMember] public string EmailAddress { set; get; } [DataMember] public string EmployeeId { set; get; } [DataMember] public string Department { set; get; } [DataMember] public string BusinessPhone { get; set; } [DataMember] public string Telephone { get; set; } [DataMember] public string SipAccount { set; get; } [DataMember] public string PrimaryHomeServerDn { get; set; } [DataMember] public string PoolName { set; get; } [DataMember] public string PhysicalDeliveryOfficeName { set; get; } [DataMember] public string OtherTelphone { get; set; } [DataMember] public string Message { get; set; } } }```
f70b744a-3d03-4117-9a61-77d3303f54af
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using MediatR; using NLog; using SFA.DAS.EmployerUsers.Application.Commands.DeleteUser; using SFA.DAS.EmployerUsers.Application.Queries.GetUsersWithExpiredRegistrations; namespace SFA.DAS.EmployerUsers.RegistrationTidyUpJob.RegistrationManagement { public class RegistrationManager { private readonly IMediator _mediator; private readonly ILogger _logger; public RegistrationManager(IMediator mediator, ILogger logger) { _mediator = mediator; _logger = logger; } public async Task RemoveExpiredRegistrations() { _logger.Info("Starting deletion of expired registrations"); try { var users = await _mediator.SendAsync(new GetUsersWithExpiredRegistrationsQuery()); _logger.Info($"Found {users.Length} users with expired registrations"); foreach (var user in users) { _logger.Info($"Deleting user with email '{user.Email}' (id: '{user.Id}')"); await _mediator.SendAsync(new DeleteUserCommand { User = user }); } } catch (Exception ex) { _logger.Error(ex); throw; } _logger.Info("Finished deletion of expired registrations"); } } } ``` Add log for audit api
```c# using System; using System.Threading.Tasks; using MediatR; using Microsoft.Azure; using NLog; using SFA.DAS.EmployerUsers.Application.Commands.DeleteUser; using SFA.DAS.EmployerUsers.Application.Queries.GetUsersWithExpiredRegistrations; namespace SFA.DAS.EmployerUsers.RegistrationTidyUpJob.RegistrationManagement { public class RegistrationManager { private readonly IMediator _mediator; private readonly ILogger _logger; public RegistrationManager(IMediator mediator, ILogger logger) { _mediator = mediator; _logger = logger; } public async Task RemoveExpiredRegistrations() { _logger.Info("Starting deletion of expired registrations"); _logger.Info($"AuditApiBaseUrl: {CloudConfigurationManager.GetSetting("AuditApiBaseUrl")}"); try { var users = await _mediator.SendAsync(new GetUsersWithExpiredRegistrationsQuery()); _logger.Info($"Found {users.Length} users with expired registrations"); foreach (var user in users) { _logger.Info($"Deleting user with email '{user.Email}' (id: '{user.Id}')"); await _mediator.SendAsync(new DeleteUserCommand { User = user }); } } catch (Exception ex) { _logger.Error(ex); throw; } _logger.Info("Finished deletion of expired registrations"); } } } ```
82fbb0be-4aab-4555-85a1-ec88f1e18bea
{ "language": "C#" }
```c# using System; using System.IO; using hutel.Filters; using hutel.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace server { public class Startup { private const string _envUseBasicAuth = "HUTEL_USE_BASIC_AUTH"; // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddJsonOptions(opt => { opt.SerializerSettings.DateParseHandling = DateParseHandling.None; }); services.AddScoped<ValidateModelStateAttribute>(); services.AddMemoryCache(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(LogLevel.Trace); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } if (Environment.GetEnvironmentVariable(_envUseBasicAuth) == "1") { app.UseBasicAuthMiddleware(); } app.UseRedirectToHttpsMiddleware(); app.UseMvc(); app.UseStaticFiles(); } } } ``` Move https redirection above basic auth
```c# using System; using System.IO; using hutel.Filters; using hutel.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace server { public class Startup { private const string _envUseBasicAuth = "HUTEL_USE_BASIC_AUTH"; // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddJsonOptions(opt => { opt.SerializerSettings.DateParseHandling = DateParseHandling.None; }); services.AddScoped<ValidateModelStateAttribute>(); services.AddMemoryCache(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(LogLevel.Trace); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRedirectToHttpsMiddleware(); if (Environment.GetEnvironmentVariable(_envUseBasicAuth) == "1") { app.UseBasicAuthMiddleware(); } app.UseMvc(); app.UseStaticFiles(); } } } ```
af59dfbe-c2a7-422c-abd0-33bb91c6ba4c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RailPhase.Demo { class Program { static void Main(string[] args) { // Create a simple web app and serve content on to URLs. var app = new App(); // Define the URL patterns to respond to incoming requests. // Any request that does not match one of these patterns will // be served by app.NotFoundView, which defaults to a simple // 404 message. // Easiest way to respond to a request: return a string app.AddStringView("^/$", (request) => "Hello World"); // More complex response, see below app.AddStringView("^/info$", InfoView); // Start listening for HTTP requests. Default port is 8080. // This method does never return! app.RunHttpServer(); // Now you should be able to visit me in your browser on http://localhost:8080 } /// <summary> /// A view that generates a simple request info page /// </summary> static string InfoView(RailPhase.Context context) { // Get the template for the info page. var render = Template.FromFile("InfoTemplate.html"); // Pass the HttpRequest as the template context, because we want // to display information about the request. Normally, we would // pass some custom object here, containing the information we // want to display. return render(null, context); } } public class DemoData { public string Heading; public string Username; } } ``` Use port for demo application that doesn't need privileges
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RailPhase.Demo { class Program { static void Main(string[] args) { // Create a simple web app and serve content on to URLs. var app = new App(); // Define the URL patterns to respond to incoming requests. // Any request that does not match one of these patterns will // be served by app.NotFoundView, which defaults to a simple // 404 message. // Easiest way to respond to a request: return a string app.AddStringView("^/$", (request) => "Hello World"); // More complex response, see below app.AddStringView("^/info$", InfoView); // Start listening for HTTP requests. Default port is 8080. // This method does never return! app.RunHttpServer("http://localhost:18080/"); // Now you should be able to visit me in your browser on http://localhost:18080/ } /// <summary> /// A view that generates a simple request info page /// </summary> static string InfoView(RailPhase.Context context) { // Get the template for the info page. var render = Template.FromFile("InfoTemplate.html"); // Pass the HttpRequest as the template context, because we want // to display information about the request. Normally, we would // pass some custom object here, containing the information we // want to display. return render(null, context); } } public class DemoData { public string Heading; public string Username; } } ```
e26d562b-5b82-4b44-8f27-f1275117e161
{ "language": "C#" }
```c# using System; namespace Casper { public class CasperException : Exception { public const int EXIT_CODE_COMPILATION_ERROR = 1; public const int EXIT_CODE_MISSING_TASK = 2; public const int EXIT_CODE_CONFIGURATION_ERROR = 3; public const int EXIT_CODE_TASK_FAILED = 4; public const int EXIT_CODE_UNHANDLED_EXCEPTION = 255; private readonly int exitCode; public CasperException(int exitCode, string message, params object[] args) : base(string.Format(message, args)) { this.exitCode = exitCode; } public CasperException(int exitCode, Exception innerException) : base(innerException.Message, innerException) { this.exitCode = exitCode; } public int ExitCode { get { return exitCode; } } } } ``` Fix formatting exception when script compilation fails with certain error messages
```c# using System; namespace Casper { public class CasperException : Exception { public const int EXIT_CODE_COMPILATION_ERROR = 1; public const int EXIT_CODE_MISSING_TASK = 2; public const int EXIT_CODE_CONFIGURATION_ERROR = 3; public const int EXIT_CODE_TASK_FAILED = 4; public const int EXIT_CODE_UNHANDLED_EXCEPTION = 255; private readonly int exitCode; public CasperException(int exitCode, string message) : base(message) { this.exitCode = exitCode; } public CasperException(int exitCode, string message, params object[] args) : this(exitCode, string.Format(message, args)) { } public CasperException(int exitCode, Exception innerException) : base(innerException.Message, innerException) { this.exitCode = exitCode; } public int ExitCode { get { return exitCode; } } } } ```
063804b2-12f4-41c2-880a-8e98f211cef7
{ "language": "C#" }
```c# using Raven.Abstractions.Data; using System; namespace Dotnet.Microservice.Health.Checks { public class RavenDbHealthCheck { public static HealthResponse CheckHealth(string connectionString) { try { ConnectionStringParser<RavenConnectionStringOptions> parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString); parser.Parse(); var store = new Raven.Client.Document.DocumentStore { Url = parser.ConnectionStringOptions.Url, DefaultDatabase = parser.ConnectionStringOptions.DefaultDatabase }; store.Initialize(); return HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase }); } catch (Exception ex) { return HealthResponse.Unhealthy(ex); } } } } ``` Make the client request the RavenDB server version. If we don't do this the client doesn't appear to raise an exception in the case of a dead server so the health check will still return healthy.
```c# using Raven.Abstractions.Data; using System; namespace Dotnet.Microservice.Health.Checks { public class RavenDbHealthCheck { public static HealthResponse CheckHealth(string connectionString) { try { ConnectionStringParser<RavenConnectionStringOptions> parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString); parser.Parse(); var store = new Raven.Client.Document.DocumentStore { Url = parser.ConnectionStringOptions.Url, DefaultDatabase = parser.ConnectionStringOptions.DefaultDatabase }; store.Initialize(); // Client doesn't seem to throw an exception until we try to do something so let's just do something simple and get the build number of the server. var build = store.DatabaseCommands.GlobalAdmin.GetBuildNumber(); // Dispose the store object store.Dispose(); return HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase, serverBuild = build.BuildVersion }); } catch (Exception ex) { return HealthResponse.Unhealthy(ex); } } } } ```
20d4ed27-075b-41e7-8442-0451a2624ec1
{ "language": "C#" }
```c# using System; namespace GraphQL.Types { public interface IInputObjectGraphType : IComplexGraphType { } public class InputObjectGraphType : InputObjectGraphType<object> { } public class InputObjectGraphType<TSourceType> : ComplexGraphType<TSourceType>, IInputObjectGraphType { public override FieldType AddField(FieldType fieldType) { if(fieldType.Type == typeof(ObjectGraphType)) { throw new ArgumentException(nameof(fieldType.Type), "InputObjectGraphType cannot have fields containing a ObjectGraphType."); } return base.AddField(fieldType); } } } ``` Fix argument name param order
```c# using System; namespace GraphQL.Types { public interface IInputObjectGraphType : IComplexGraphType { } public class InputObjectGraphType : InputObjectGraphType<object> { } public class InputObjectGraphType<TSourceType> : ComplexGraphType<TSourceType>, IInputObjectGraphType { public override FieldType AddField(FieldType fieldType) { if(fieldType.Type == typeof(ObjectGraphType)) { throw new ArgumentException("InputObjectGraphType cannot have fields containing a ObjectGraphType.", nameof(fieldType.Type)); } return base.AddField(fieldType); } } } ```
f63b09df-acab-4e2a-b84f-aaf2c672cabc
{ "language": "C#" }
```c# using FluentEmail.Core; using FluentScheduler; using System; namespace BatteryCommander.Web.Jobs { public class SqliteBackupJob : IJob { private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable private readonly IFluentEmail emailSvc; public SqliteBackupJob(IFluentEmail emailSvc) { this.emailSvc = emailSvc; } public virtual void Execute() { emailSvc .To(Recipient) .Subject("Nightly Db Backup") .Body("Please find the nightly database backup attached.") .Attach(new FluentEmail.Core.Models.Attachment { ContentType = "application/octet-stream", Filename = "Data.db", Data = System.IO.File.OpenRead("Data.db") }) .Send(); } } }``` Switch to new backup email recipient
```c# using FluentEmail.Core; using FluentScheduler; using System; namespace BatteryCommander.Web.Jobs { public class SqliteBackupJob : IJob { private const String Recipient = "Backups@RedLeg.app"; private readonly IFluentEmail emailSvc; public SqliteBackupJob(IFluentEmail emailSvc) { this.emailSvc = emailSvc; } public virtual void Execute() { emailSvc .To(Recipient) .Subject("Nightly Db Backup") .Body("Please find the nightly database backup attached.") .Attach(new FluentEmail.Core.Models.Attachment { ContentType = "application/octet-stream", Filename = "Data.db", Data = System.IO.File.OpenRead("Data.db") }) .Send(); } } } ```
97161acf-27b5-4f99-8e91-136f2dea827b
{ "language": "C#" }
```c# using System; using LinqToTTreeInterfacesLib; using LINQToTTreeLib.Utils; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; Declare = false; } public IValue InitialValue { get; set; } /// <summary> /// Get/Set if this variable needs to be declared. /// </summary> public bool Declare { get; set; } /// <summary> /// TO help with debugging... /// </summary> /// <returns></returns> public override string ToString() { return VariableName + " = (" + Type.Name + ") " + RawValue; } public void RenameRawValue(string oldname, string newname) { if (InitialValue != null) InitialValue.RenameRawValue(oldname, newname); if (RawValue == oldname) { RawValue = newname; VariableName = newname; } } } } ``` Fix up how we generate debugging info for var simple.
```c# using System; using LinqToTTreeInterfacesLib; using LINQToTTreeLib.Utils; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; Declare = false; } public IValue InitialValue { get; set; } /// <summary> /// Get/Set if this variable needs to be declared. /// </summary> public bool Declare { get; set; } /// <summary> /// TO help with debugging... /// </summary> /// <returns></returns> public override string ToString() { var s = string.Format("{0} {1}", Type.Name, VariableName); if (InitialValue != null) s = string.Format("{0} = {1}", s, InitialValue.RawValue); return s; } public void RenameRawValue(string oldname, string newname) { if (InitialValue != null) InitialValue.RenameRawValue(oldname, newname); if (RawValue == oldname) { RawValue = newname; VariableName = newname; } } } } ```
74c44d96-cd9d-4151-a5dd-08787ca4d9e8
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } } ``` Add editor button to update build path
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } if (GUILayout.Button("Update Build Path")) { collection.updateBuildPath(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } } ```
1a279c65-0882-4754-8224-cb565c780476
{ "language": "C#" }
```c# using System; namespace DynamixelServo.Quadruped { static class MathExtensions { public static double RadToDegree(this double angle) { return angle * (180.0 / Math.PI); } public static float RadToDegree(this float angle) { return angle * (180f / (float)Math.PI); } public static double DegreeToRad(this double angle) { return Math.PI * angle / 180.0; } public static float DegreeToRad(this float angle) { return (float)Math.PI * angle / 180f; } public static double ToPower(this double number, double powerOf) { return Math.Pow(number, powerOf); } } } ``` Add square extension method to floats
```c# using System; namespace DynamixelServo.Quadruped { static class MathExtensions { public static double RadToDegree(this double angle) { return angle * (180.0 / Math.PI); } public static float RadToDegree(this float angle) { return angle * (180f / (float)Math.PI); } public static double DegreeToRad(this double angle) { return Math.PI * angle / 180.0; } public static float DegreeToRad(this float angle) { return (float)Math.PI * angle / 180f; } public static double ToPower(this double number, double powerOf) { return Math.Pow(number, powerOf); } public static float Square(this float number) { return number * number; } } } ```
a02eb3ac-d808-4ce0-ba99-6a11c1522034
{ "language": "C#" }
```c# using System; using Eto.Forms; using JabbR.Eto.Interface.Dialogs; using JabbR.Eto.Model.JabbR; using System.Diagnostics; namespace JabbR.Eto.Actions { public class AddServer : ButtonAction { public const string ActionID = "AddServer"; public bool AutoConnect { get; set; } public AddServer () { this.ID = ActionID; this.MenuText = "Add Server..."; } protected override void OnActivated (EventArgs e) { base.OnActivated (e); var server = new JabbRServer { Name = "JabbR.net", Address = "http://jabbr.net", JanrainAppName = "jabbr" }; using (var dialog = new ServerDialog(server, true, true)) { dialog.DisplayMode = DialogDisplayMode.Attached; var ret = dialog.ShowDialog (Application.Instance.MainForm); if (ret == DialogResult.Ok) { Debug.WriteLine ("Added Server, Name: {0}", server.Name); var config = JabbRApplication.Instance.Configuration; config.AddServer (server); JabbRApplication.Instance.SaveConfiguration (); if (AutoConnect) { Application.Instance.AsyncInvoke(delegate { server.Connect (); }); } } } } } } ``` Use https by default for new servers
```c# using System; using Eto.Forms; using JabbR.Eto.Interface.Dialogs; using JabbR.Eto.Model.JabbR; using System.Diagnostics; namespace JabbR.Eto.Actions { public class AddServer : ButtonAction { public const string ActionID = "AddServer"; public bool AutoConnect { get; set; } public AddServer () { this.ID = ActionID; this.MenuText = "Add Server..."; } protected override void OnActivated (EventArgs e) { base.OnActivated (e); var server = new JabbRServer { Name = "JabbR.net", Address = "https://jabbr.net", JanrainAppName = "jabbr" }; using (var dialog = new ServerDialog(server, true, true)) { dialog.DisplayMode = DialogDisplayMode.Attached; var ret = dialog.ShowDialog (Application.Instance.MainForm); if (ret == DialogResult.Ok) { Debug.WriteLine ("Added Server, Name: {0}", server.Name); var config = JabbRApplication.Instance.Configuration; config.AddServer (server); JabbRApplication.Instance.SaveConfiguration (); if (AutoConnect) { Application.Instance.AsyncInvoke(delegate { server.Connect (); }); } } } } } } ```
03475418-0aeb-4c19-b53b-76ce8a46e2b8
{ "language": "C#" }
```c# @inherits Umbraco.Web.Mvc.UmbracoTemplatePage @{ Layout = "_Layout.cshtml"; } @{ Html.RenderPartial("PageHeading"); } <div class="row"> <div class="small-12 large-12 columns"> @{ var members = Umbraco.TypedContentAtXPath("//OrganizationMember") .Where(m => m.GetPropertyValue<string>("Position") != "Coach"); } <ul class="small-block-grid-2 medium-block-grid-4 large-block-grid-4"> @foreach (var item in members) { <li> <div class="panel-box"> <div class="row"> <div class="large-12 columns"> @if (item.HasValue("ProfilePhoto")) { <div class="img-container ratio-2-3"> <img src="@item.GetPropertyValue("ProfilePhoto")" /> </div> } <h5 class="text-center"> @item.GetPropertyValue("FirstName") @item.GetPropertyValue("LastName") </h5> @if (item.HasValue("HomeTown")) { <p class="text-center">@item.GetPropertyValue("HomeTown")</p> } </div> </div> </div> </li> } </ul> </div> </div> ``` Order organization members by name.
```c# @inherits Umbraco.Web.Mvc.UmbracoTemplatePage @{ Layout = "_Layout.cshtml"; } @{ Html.RenderPartial("PageHeading"); } <div class="row"> <div class="small-12 large-12 columns"> @{ var members = Umbraco.TypedContentAtXPath("//OrganizationMember") .Where(m => m.GetPropertyValue<string>("Position") != "Coach") .OrderBy(m => m.GetPropertyValue("LastName")) .ThenBy(m => m.GetPropertyValue("FirstName")); } <ul class="small-block-grid-2 medium-block-grid-4 large-block-grid-4"> @foreach (var item in members) { <li> <div class="panel-box"> <div class="row"> <div class="large-12 columns"> @if (item.HasValue("ProfilePhoto")) { <div class="img-container ratio-2-3"> <img src="@item.GetPropertyValue("ProfilePhoto")" /> </div> } <h5 class="text-center"> @item.GetPropertyValue("FirstName") @item.GetPropertyValue("LastName") </h5> @if (item.HasValue("HomeTown")) { <p class="text-center">@item.GetPropertyValue("HomeTown")</p> } </div> </div> </div> </li> } </ul> </div> </div> ```
d5a97343-f12f-4608-9322-8847e5e5bb77
{ "language": "C#" }
```c# using System; using MonoTouch.Foundation; using MonoTouch.UIKit; using Eto.Platform.iOS.Forms; using Eto.Forms; namespace Eto.Platform.iOS { [MonoTouch.Foundation.Register("EtoAppDelegate")] public class EtoAppDelegate : UIApplicationDelegate { public EtoAppDelegate () { } public override bool WillFinishLaunching (UIApplication application, NSDictionary launchOptions) { ApplicationHandler.Instance.Initialize(this); return true; } } } ``` Fix running on < iOS 6.0
```c# using System; using MonoTouch.Foundation; using MonoTouch.UIKit; using Eto.Platform.iOS.Forms; using Eto.Forms; namespace Eto.Platform.iOS { [MonoTouch.Foundation.Register("EtoAppDelegate")] public class EtoAppDelegate : UIApplicationDelegate { public EtoAppDelegate () { } public override bool FinishedLaunching (UIApplication application, NSDictionary launcOptions) { ApplicationHandler.Instance.Initialize(this); return true; } } } ```
aec00b76-560f-4f2f-abad-d4ccf2c85043
{ "language": "C#" }
```c# using Newtonsoft.Json; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class QuestionDisplayOptionsCustomOptions { } }``` Add custom display option props based on sliders
```c# using Newtonsoft.Json; using System.Collections.Generic; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class QuestionDisplayOptionsCustomOptions { public List<string> OptionSet { get; set; } public int StartingPosition { get; set; } public int StepSize { get; set; } } }```
865a8c4e-b6cc-465f-bc89-8fe292ccf622
{ "language": "C#" }
```c# using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace Presentation.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Turns off self reference looping when serializing models in API controlllers GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // Support polymorphism in web api JSON output GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //Format datetime correctly. From: http://stackoverflow.com/questions/20143739/date-format-in-mvc-4-api-controller var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings .Converters.Add(dateTimeConverter); } } } ``` Convert all dates to UTC time
```c# using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Presentation.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Turns off self reference looping when serializing models in API controlllers GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // Support polymorphism in web api JSON output GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Convert all dates to UTC GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; } } } ```
8fba020a-fe39-4407-b81b-d58a02c583d6
{ "language": "C#" }
```c# namespace BmpListener.Bgp { public class ASPathSegment { public ASPathSegment(Type type, int[] asns) { SegmentType = Type; ASNs = asns; } public enum Type { AS_SET = 1, AS_SEQUENCE, AS_CONFED_SEQUENCE, AS_CONFED_SET } public Type SegmentType { get; set; } public int[] ASNs { get; set; } } }``` Change ASN int array to IList
```c# using System.Collections.Generic; namespace BmpListener.Bgp { public class ASPathSegment { public ASPathSegment(Type type, IList<int> asns) { SegmentType = type; ASNs = asns; } public enum Type { AS_SET = 1, AS_SEQUENCE, AS_CONFED_SEQUENCE, AS_CONFED_SET } public Type SegmentType { get; set; } public IList<int> ASNs { get; set; } } }```
3d97d2c5-ec66-4be2-89aa-aba6ef19f67e
{ "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("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [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("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")] ``` Bump assembly info for 1.2.2 release
```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("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [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("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.2.2.0")] [assembly: AssemblyFileVersion("1.2.2.0")] ```
51fc1a92-965d-4208-831b-a9610583dd47
{ "language": "C#" }
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Input.Editor { [CustomEditor(typeof(MixedRealityControllerVisualizer))] public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { } }``` Use inspector for child classes
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Input.Editor { [CustomEditor(typeof(MixedRealityControllerVisualizer), true)] public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { } }```
211ae9e3-9aef-4c19-aa38-20cb6d661629
{ "language": "C#" }
```c# using System.Diagnostics.CodeAnalysis; using System.Web.Optimization; namespace T4MVCHostMvcApp.App_Start { public static class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle(Links.Bundles.Content.Styles).Include( Links.Bundles.Content.Assets.Site_css )); } } } namespace Links { public static partial class Bundles { public static partial class Content { public const string Styles = "~/content/styles"; } } }``` Update bundle config to match exampe in wiki page
```c# using System.Diagnostics.CodeAnalysis; using System.Web.Optimization; namespace T4MVCHostMvcApp.App_Start { public static class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle(Links.Bundles.Scripts.jquery).Include("~/scripts/jquery-{version}.js")); bundles.Add(new StyleBundle(Links.Bundles.Styles.bootstrap).Include("~/styles/bootstrap*.css")); bundles.Add(new StyleBundle(Links.Bundles.Styles.common).Include(Links.Bundles.Content.Assets.Site_css)); } } } namespace Links { public static partial class Bundles { public static partial class Scripts { public static readonly string jquery = "~/scripts/jquery"; public static readonly string jqueryui = "~/scripts/jqueryui"; } public static partial class Styles { public static readonly string bootstrap = "~/styles/boostrap"; public static readonly string theme = "~/styles/theme"; public static readonly string common = "~/styles/common"; } } }```
b12d67c7-4542-4226-9933-e26dc56882fe
{ "language": "C#" }
```c# using System.Collections.Generic; namespace slang.Lexing.Trees.Nodes { public class Transitions : Dictionary<char,Node> { } } ``` Use character class as transition key
```c# using System.Collections.Generic; namespace slang.Lexing.Trees.Nodes { public class Transitions : Dictionary<Character,Transition> { } } ```
39f74100-eadd-4fe2-9948-81b7261985be
{ "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 SmugMug.v2.Authentication; using System.Threading.Tasks; namespace SmugMug.v2.Types { public class SiteEntity : SmugMugEntity { public SiteEntity(OAuthToken token) { _oauthToken = token; } public async Task<UserEntity> GetAuthenticatedUserAsync() { // !authuser string requestUri = string.Format("{0}!authuser", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityAsync<UserEntity>(requestUri); } public async Task<UserEntity[]> SearchForUser(string query) { // api/v2/user!search?q= string requestUri = string.Format("{0}/user!search?q={1}", SmugMug.v2.Constants.Addresses.SmugMugApi, query); return await RetrieveEntityArrayAsync<UserEntity>(requestUri); } } } ``` Add a way to get the vendors from the Site entity.
```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 SmugMug.v2.Authentication; using System.Threading.Tasks; namespace SmugMug.v2.Types { public class SiteEntity : SmugMugEntity { public SiteEntity(OAuthToken token) { _oauthToken = token; } public async Task<UserEntity> GetAuthenticatedUserAsync() { // !authuser string requestUri = string.Format("{0}!authuser", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityAsync<UserEntity>(requestUri); } public async Task<CatalogVendorEntity[]> GetVendors() { // /catalog!vendors string requestUri = string.Format("{0}/catalog!vendors", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityArrayAsync<CatalogVendorEntity>(requestUri); } public async Task<UserEntity[]> SearchForUser(string query) { // api/v2/user!search?q= string requestUri = string.Format("{0}/user!search?q={1}", SmugMug.v2.Constants.Addresses.SmugMugApi, query); return await RetrieveEntityArrayAsync<UserEntity>(requestUri); } } } ```
e0d8730f-66e2-4fa1-8075-0ce28069559c
{ "language": "C#" }
```c# using System.ComponentModel.Composition; using Microsoft.EntityFrameworkCore; using Waf.BookLibrary.Library.Applications.Data; using Waf.BookLibrary.Library.Applications.Services; using Waf.BookLibrary.Library.Domain; namespace Test.BookLibrary.Library.Applications.Services { [Export, Export(typeof(IDBContextService))] public class MockDBContextService : IDBContextService { public DbContext GetBookLibraryContext(out string dataSourcePath) { dataSourcePath = @"C:\Test.db"; var options = new DbContextOptionsBuilder<BookLibraryContext>().UseInMemoryDatabase(databaseName: "TestDatabase").Options; var context = new BookLibraryContext(options, modelBuilder => { modelBuilder.Entity<Book>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); modelBuilder.Entity<Person>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); }); return context; } } } ``` Fix InMemory context for unit tests
```c# using System.ComponentModel.Composition; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Waf.BookLibrary.Library.Applications.Data; using Waf.BookLibrary.Library.Applications.Services; using Waf.BookLibrary.Library.Domain; namespace Test.BookLibrary.Library.Applications.Services { [Export, Export(typeof(IDBContextService))] public class MockDBContextService : IDBContextService { public DbContext GetBookLibraryContext(out string dataSourcePath) { dataSourcePath = @"C:\Test.db"; var options = new DbContextOptionsBuilder<BookLibraryContext>().UseInMemoryDatabase(databaseName: "TestDatabase", databaseRoot: new InMemoryDatabaseRoot()).Options; var context = new BookLibraryContext(options, modelBuilder => { modelBuilder.Entity<Book>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); modelBuilder.Entity<Person>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); }); return context; } } } ```
b4a6f2a3-d019-46fe-8b4f-7e861b89aee4
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsEnumDropdown<T> : SettingsDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new DropdownControl(); protected new class DropdownControl : OsuEnumDropdown<T> { public DropdownControl() { Margin = new MarginPadding { Top = 5 }; RelativeSizeAxes = Axes.X; } protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 200); } } } ``` Refactor the menu's max height to be a property
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsEnumDropdown<T> : SettingsDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new DropdownControl(); protected new class DropdownControl : OsuEnumDropdown<T> { protected virtual int MenuMaxHeight => 200; public DropdownControl() { Margin = new MarginPadding { Top = 5 }; RelativeSizeAxes = Axes.X; } protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = MenuMaxHeight); } } } ```
52359040-cb0d-45f1-b9b9-7b5046e8929d
{ "language": "C#" }
```c# // Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com) // // This file is part of the HealthBar extension for Unity. Licensed under the // MIT license. See LICENSE file in the project root folder. Based on HealthBar // component made by Zero3Growlithe (zero3growlithe@gmail.com). using UnityEngine; namespace HealthBarEx { [System.Serializable] // todo encapsulate fields public class HealthBarGUI { public Color addedHealth; [HideInInspector] public float alpha; public float animationSpeed = 3f; public Color availableHealth; public Color displayedValue; public bool displayValue = true; public Color drainedHealth; public int height = 30; public Vector2 offset = new Vector2(0, 30); public PositionModes positionMode; public GUIStyle textStyle; public Texture texture; public float transitionDelay = 3f; public float transitionSpeed = 5f; public Vector2 valueOffset = new Vector2(0, 30); public float visibility = 1; public int width = 100; public enum PositionModes { Fixed, Center }; } }``` Reorder fields in the inspector
```c# // Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com) // // This file is part of the HealthBar extension for Unity. Licensed under the // MIT license. See LICENSE file in the project root folder. Based on HealthBar // component made by Zero3Growlithe (zero3growlithe@gmail.com). using UnityEngine; namespace HealthBarEx { [System.Serializable] // todo encapsulate fields public class HealthBarGUI { [HideInInspector] public float alpha; public bool displayValue = true; public PositionModes positionMode; public Texture texture; public Color addedHealth; public Color availableHealth; public Color displayedValue; public Color drainedHealth; public float animationSpeed = 3f; public float transitionSpeed = 5f; public float transitionDelay = 3f; public float visibility = 1; public int width = 100; public int height = 30; public Vector2 offset = new Vector2(0, 30); public Vector2 valueOffset = new Vector2(0, 30); public GUIStyle textStyle; public enum PositionModes { Fixed, Center }; } }```
f69421c3-a712-4197-b712-5633f724f6a3
{ "language": "C#" }
```c# using System; using FluentAssertions; using Xunit; namespace Grobid.PdfToXml.Test { public class TokenBlockFactoryTest { [Fact] public void TestA() { var stub = new TextRenderInfoStub(); var testSubject = new TokenBlockFactory(100, 100); Action test = () => testSubject.Create(stub); test.ShouldThrow<NullReferenceException>("I am still implementing the code."); } } } ``` Write test to ensure characters are normalized.
```c# using System; using FluentAssertions; using iTextSharp.text.pdf.parser; using Xunit; namespace Grobid.PdfToXml.Test { public class TokenBlockFactoryTest { [Fact] public void FactoryShouldNormalizeUnicodeStrings() { var stub = new TextRenderInfoStub { AscentLine = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)), Baseline = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)), DescentLine = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)), PostscriptFontName = "CHUFSU+NimbusRomNo9L-Medi", Text = "abcd\u0065\u0301fgh", }; var testSubject = new TokenBlockFactory(100, 100); var tokenBlock = testSubject.Create(stub); stub.Text.ToCharArray().Should().HaveCount(9); tokenBlock.Text.ToCharArray().Should().HaveCount(8); } } } ```
57df967c-351f-4256-91ee-fbabefbd623e
{ "language": "C#" }
```c# // Copyright(c) 2016 Google Inc. // // 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.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public ActionResult Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } } ``` Simplify Login() action - no explicit return necessary
```c# // Copyright(c) 2016 Google Inc. // // 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.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public void Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } } ```
1515e8e4-940f-451e-9e6e-ec3ea12aba41
{ "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.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterfaceV2; using osu.Game.Skinning; using osuTK.Graphics; namespace osu.Game.Screens.Edit.Setup { internal class ColoursSection : SetupSection { public override LocalisableString Title => "Colours"; private LabelledColourPalette comboColours; [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { comboColours = new LabelledColourPalette { Label = "Hitcircle / Slider Combos", FixedLabelWidth = LABEL_WIDTH, ColourNamePrefix = "Combo" } }; var colours = Beatmap.BeatmapSkin?.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value; if (colours != null) comboColours.Colours.AddRange(colours.Select(c => (Colour4)c)); } } } ``` Use editable skin structure in combo colour picker
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Screens.Edit.Setup { internal class ColoursSection : SetupSection { public override LocalisableString Title => "Colours"; private LabelledColourPalette comboColours; [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { comboColours = new LabelledColourPalette { Label = "Hitcircle / Slider Combos", FixedLabelWidth = LABEL_WIDTH, ColourNamePrefix = "Combo" } }; if (Beatmap.BeatmapSkin != null) comboColours.Colours.BindTo(Beatmap.BeatmapSkin.ComboColours); } } } ```
b3af441d-612b-40e6-803b-4ca28c65bc20
{ "language": "C#" }
```c# using System.Collections.Generic; using commercetools.Common; using commercetools.CustomFields; using Newtonsoft.Json; namespace commercetools.Carts { /// <summary> /// API representation for creating a new CustomLineItem. /// </summary> /// <see href="http://dev.commercetools.com/http-api-projects-carts.html#customlineitemdraft"/> public class CustomLineItemDraft { #region Properties [JsonProperty(PropertyName = "name")] public LocalizedString Name { get; set; } [JsonProperty(PropertyName = "quantity")] public int? Quantity { get; set; } [JsonProperty(PropertyName = "money")] public Money Money { get; set; } [JsonProperty(PropertyName = "slug")] public string Slug { get; set; } [JsonProperty(PropertyName = "taxCategory")] public Reference TaxCategory { get; set; } [JsonProperty(PropertyName = "custom")] public List<CustomFieldsDraft> Custom { get; set; } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> public CustomLineItemDraft(LocalizedString name) { this.Name = name; } #endregion } } ``` Update Custom field to the correct POCO representation
```c# using System.Collections.Generic; using commercetools.Common; using commercetools.CustomFields; using Newtonsoft.Json; namespace commercetools.Carts { /// <summary> /// API representation for creating a new CustomLineItem. /// </summary> /// <see href="http://dev.commercetools.com/http-api-projects-carts.html#customlineitemdraft"/> public class CustomLineItemDraft { #region Properties [JsonProperty(PropertyName = "name")] public LocalizedString Name { get; set; } [JsonProperty(PropertyName = "quantity")] public int? Quantity { get; set; } [JsonProperty(PropertyName = "money")] public Money Money { get; set; } [JsonProperty(PropertyName = "slug")] public string Slug { get; set; } [JsonProperty(PropertyName = "taxCategory")] public Reference TaxCategory { get; set; } [JsonProperty(PropertyName = "custom")] public CustomFieldsDraft Custom { get; set; } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> public CustomLineItemDraft(LocalizedString name) { this.Name = name; } #endregion } } ```
73a2c7a8-8e9d-4179-bfb5-bac09c6fb967
{ "language": "C#" }
```c# namespace Cronofy { using System; /// <summary> /// Interface for a Cronofy client base that manages the /// access token and any shared client methods. /// </summary> public interface ICronofyUserInfoClient { /// <summary> /// Gets the user info belonging to the account. /// </summary> /// <returns>The account's user info.</returns> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="request"/> is null. /// </exception> /// <exception cref="CronofyException"> /// Thrown if an error is encountered whilst making the request. /// </exception> UserInfo GetUserInfo(); } } ``` Remove unnecessary argument exception documentation on user info
```c# namespace Cronofy { using System; /// <summary> /// Interface for a Cronofy client base that manages the /// access token and any shared client methods. /// </summary> public interface ICronofyUserInfoClient { /// <summary> /// Gets the user info belonging to the account. /// </summary> /// <returns>The account's user info.</returns> /// <exception cref="CronofyException"> /// Thrown if an error is encountered whilst making the request. /// </exception> UserInfo GetUserInfo(); } } ```
ff9f75e7-44c7-42a6-8a79-30cd4f9338ee
{ "language": "C#" }
```c# namespace MyParcelApi.Net.Models { public enum Carrier { PostNl = 1, BPost = 2 } } ``` Improve when there is no carrier
```c# namespace MyParcelApi.Net.Models { public enum Carrier { None = 0, PostNl = 1, BPost = 2 } } ```
1970f4a9-d5f4-4381-a73d-8453b1944352
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class ShotControl : MonoBehaviour { public float speed = 0.2f; private bool inBlock; private int life = 3; void Start () { } void Update () { // Old position Vector3 position = transform.position; // Move transform.Translate(Vector3.up * speed); // Check for collision Collider2D collider = Physics2D.OverlapCircle(transform.position, 0.1f); if (collider) { if (collider.name == "ArenaBlock") { if (!inBlock) { // Reduce life if (--life == 0) { Destroy(gameObject); return; } // Find vector to block center (normalized for stretched blocks) Vector3 v = collider.transform.position - position; v.x /= collider.transform.localScale.x; v.y /= collider.transform.localScale.y; Vector3 forward = transform.up; if (Mathf.Abs(v.x) < Mathf.Abs(v.y)) { forward.y = -forward.y; // bounce vertically } else { forward.x = -forward.x; // bounce horizontally } transform.up = forward; } inBlock = true; } } else { inBlock = false; } } } ``` Check for shots going out of bounds and kill them
```c# using UnityEngine; using System.Collections; public class ShotControl : MonoBehaviour { public float speed = 0.2f; private bool inBlock; private int life = 3; void Start () { } void Update () { // Old position Vector3 position = transform.position; // Move transform.Translate(Vector3.up * speed); // Check for out of bounds if (100f <= Mathf.Abs(transform.position.magnitude)) { Destroy(gameObject); return; } // Check for collision Collider2D collider = Physics2D.OverlapCircle(transform.position, 0.15f); if (collider) { if (collider.name == "ArenaBlock") { if (!inBlock) { // Reduce life if (--life == 0) { Destroy(gameObject); return; } // Find vector to block center (normalized for stretched blocks) Vector3 v = collider.transform.position - position; v.x /= collider.transform.localScale.x; v.y /= collider.transform.localScale.y; Vector3 forward = transform.up; if (Mathf.Abs(v.x) < Mathf.Abs(v.y)) { forward.y = -forward.y; // bounce vertically } else { forward.x = -forward.x; // bounce horizontally } transform.up = forward; } inBlock = true; } } else { inBlock = false; } } } ```
ad936b6c-b859-4b80-bfa8-3cc8bd7c43b0
{ "language": "C#" }
```c# using WootzJs.Mvc.Views; using WootzJs.Mvc.Views.Css; namespace WootzJs.Mvc { public static class StyleExtensions { public static T WithBold<T>(this T control) where T : Control { control.Style.Font.Weight = new CssFontWeight(CssFontWeightType.Bold); return control; } } }``` Add more style extension methods
```c# using WootzJs.Mvc.Views; using WootzJs.Mvc.Views.Css; namespace WootzJs.Mvc { public static class StyleExtensions { public static T WithBold<T>(this T control) where T : Control { control.Style.Font.Weight = new CssFontWeight(CssFontWeightType.Bold); return control; } public static T WithPadding<T>(this T control, CssPadding padding) where T : Control { control.Style.Padding = padding; return control; } } }```
dace51cf-26d3-4bb9-8abe-70591f852c4f
{ "language": "C#" }
```c# using System.Net; using System.Web.Script.Serialization; namespace MultiMiner.MobileMiner.Api { public class ApiContext { static public void SubmitMiningStatistics(string url, MiningStatistics miningStatistics) { string fullUrl = url + "/api/MiningStatisticsInput"; using (WebClient client = new WebClient()) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonData = serializer.Serialize(miningStatistics); client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.UploadString(fullUrl, jsonData); } } } } ``` Handle URL's with or without a / suffix
```c# using System.Net; using System.Web.Script.Serialization; namespace MultiMiner.MobileMiner.Api { public class ApiContext { static public void SubmitMiningStatistics(string url, MiningStatistics miningStatistics) { if (!url.EndsWith("/")) url = url + "/"; string fullUrl = url + "api/MiningStatisticsInput"; using (WebClient client = new WebClient()) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonData = serializer.Serialize(miningStatistics); client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.UploadString(fullUrl, jsonData); } } } } ```
18135345-dc1a-4158-b527-7acc420a9707
{ "language": "C#" }
```c# #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "Cake.Hg", repositoryOwner: "cake-contrib", repositoryName: "Cake.Hg", appVeyorAccountName: "cakecontrib", solutionFilePath: "./src/Cake.Hg.sln", shouldRunCodecov: false, wyamSourceFiles: "../../src/**/{!bin,!obj,!packages,!*Tests,}/**/*.cs"); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/Cake.HgTests/**/*.cs", BuildParameters.RootDirectoryPath + "/src/Cake.Hg/**/*.AssemblyInfo.cs" }); Build.Run();``` Disable dupfinder because of Hg.Net
```c# #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "Cake.Hg", repositoryOwner: "cake-contrib", repositoryName: "Cake.Hg", appVeyorAccountName: "cakecontrib", solutionFilePath: "./src/Cake.Hg.sln", shouldRunCodecov: false, shouldRunDupFinder: false, wyamSourceFiles: "../../src/**/{!bin,!obj,!packages,!*Tests,}/**/*.cs"); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/Cake.HgTests/**/*.cs", BuildParameters.RootDirectoryPath + "/src/Cake.Hg/**/*.AssemblyInfo.cs" }); Build.Run();```
09b955db-d2a6-4b81-b512-260387aa717d
{ "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("MowChat")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MowChat")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("17fb5df9-452a-423d-925e-7b98ab9a5b02")] // 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")] ``` Increase version number & add 2014 copyright
```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("MowChat")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MowChat")] [assembly: AssemblyCopyright("Copyright © 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("17fb5df9-452a-423d-925e-7b98ab9a5b02")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ```
4f8b9611-fc4d-4b1a-a9ba-c2394c920571
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.DomainServices")] [assembly: AssemblyDescription("Autofac Integration for RIA Services")] [assembly: ComVisible(false)]``` 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; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.DomainServices")] [assembly: ComVisible(false)]```
03a07414-9781-4c76-afbd-cd569294ea70
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Audio.Track; using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Beatmaps { public partial class WorkingBeatmap { /// <summary> /// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>. /// </summary> protected class VirtualBeatmapTrack : TrackVirtual { private readonly IBeatmap beatmap; public VirtualBeatmapTrack(IBeatmap beatmap) { this.beatmap = beatmap; updateVirtualLength(); } protected override void UpdateState() { updateVirtualLength(); base.UpdateState(); } private void updateVirtualLength() { var lastObject = beatmap.HitObjects.LastOrDefault(); switch (lastObject) { case null: Length = 1000; break; case IHasEndTime endTime: Length = endTime.EndTime + 1000; break; default: Length = lastObject.StartTime + 1000; break; } } } } } ``` Use a const for excess length
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Audio.Track; using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Beatmaps { public partial class WorkingBeatmap { /// <summary> /// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>. /// </summary> protected class VirtualBeatmapTrack : TrackVirtual { private const double excess_length = 1000; private readonly IBeatmap beatmap; public VirtualBeatmapTrack(IBeatmap beatmap) { this.beatmap = beatmap; updateVirtualLength(); } protected override void UpdateState() { updateVirtualLength(); base.UpdateState(); } private void updateVirtualLength() { var lastObject = beatmap.HitObjects.LastOrDefault(); switch (lastObject) { case null: Length = excess_length; break; case IHasEndTime endTime: Length = endTime.EndTime + excess_length; break; default: Length = lastObject.StartTime + excess_length; break; } } } } } ```
dc98437d-35dd-43f1-b163-1becf6332cc9
{ "language": "C#" }
```c# // Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using JetBrains.Annotations; using Nuke.Core.Utilities; namespace Nuke.Core.Tooling { [PublicAPI] [DebuggerStepThrough] [DebuggerNonUserCode] public static class ProcessExtensions { [AssertionMethod] public static void AssertWaitForExit ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()"); } [AssertionMethod] public static void AssertZeroExitCode ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { process.AssertWaitForExit(); ControlFlow.Assert(process.ExitCode == 0, new[] { $"Process '{Path.GetFileName(process.StartInfo.FileName)}' exited with code {process.ExitCode}. Please verify the invocation:", $"> {process.StartInfo.FileName.DoubleQuoteIfNeeded()} {process.StartInfo.Arguments}" }.Join(EnvironmentInfo.NewLine)); } public static IEnumerable<Output> EnsureOnlyStd (this IEnumerable<Output> output) { foreach (var o in output) { ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std"); yield return o; } } } } ``` Remove printing of invocation in case of non-zero exit code.
```c# // Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using JetBrains.Annotations; using Nuke.Core.Utilities; namespace Nuke.Core.Tooling { [PublicAPI] [DebuggerStepThrough] [DebuggerNonUserCode] public static class ProcessExtensions { [AssertionMethod] public static void AssertWaitForExit ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()"); } [AssertionMethod] public static void AssertZeroExitCode ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { process.AssertWaitForExit(); ControlFlow.Assert(process.ExitCode == 0, $"Process '{Path.GetFileName(process.StartInfo.FileName)}' exited with code {process.ExitCode}. Please verify the invocation."); } public static IEnumerable<Output> EnsureOnlyStd (this IEnumerable<Output> output) { foreach (var o in output) { ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std"); yield return o; } } } } ```
2ec7d416-1d72-4e60-a3b0-4565c4bdfcd4
{ "language": "C#" }
```c# using System; using System.Drawing.Imaging; using System.IO; using Tellurium.MvcPages.Utils; namespace Tellurium.MvcPages.BrowserCamera.Storage { public class FileSystemScreenshotStorage : IScreenshotStorage { private readonly string screenshotDirectoryPath; public FileSystemScreenshotStorage(string screenshotDirectoryPath) { this.screenshotDirectoryPath = screenshotDirectoryPath; } public virtual void Persist(byte[] image, string screenshotName) { var screenshotPath = GetScreenshotPath(screenshotName); image.ToBitmap().Save(screenshotPath, ImageFormat.Jpeg); } protected string GetScreenshotPath(string screenshotName) { if (string.IsNullOrWhiteSpace(screenshotDirectoryPath)) { throw new ApplicationException("Screenshot directory path not defined"); } if (string.IsNullOrWhiteSpace(screenshotName)) { throw new ArgumentException("Screenshot name cannot be empty", nameof(screenshotName)); } var fileName = $"{screenshotName}.jpg"; return Path.Combine(screenshotDirectoryPath, fileName); } } }``` Create directory for error screenshot if it does not exist
```c# using System; using System.Drawing.Imaging; using System.IO; using Tellurium.MvcPages.Utils; namespace Tellurium.MvcPages.BrowserCamera.Storage { public class FileSystemScreenshotStorage : IScreenshotStorage { private readonly string screenshotDirectoryPath; public FileSystemScreenshotStorage(string screenshotDirectoryPath) { this.screenshotDirectoryPath = screenshotDirectoryPath; } public virtual void Persist(byte[] image, string screenshotName) { var screenshotPath = GetScreenshotPath(screenshotName); image.ToBitmap().Save(screenshotPath, ImageFormat.Jpeg); } protected string GetScreenshotPath(string screenshotName) { if (string.IsNullOrWhiteSpace(screenshotDirectoryPath)) { throw new ApplicationException("Screenshot directory path not defined"); } if (string.IsNullOrWhiteSpace(screenshotName)) { throw new ArgumentException("Screenshot name cannot be empty", nameof(screenshotName)); } if (Directory.Exists(screenshotDirectoryPath) == false) { Directory.CreateDirectory(screenshotDirectoryPath); } var fileName = $"{screenshotName}.jpg"; return Path.Combine(screenshotDirectoryPath, fileName); } } }```
de2e58d3-87dd-4436-8567-45ad6c5e861b
{ "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.Threading.Tasks; namespace Microsoft.AspNetCore.Mvc.Internal { public static class TaskCache { #if NET451 static readonly Task _completedTask = Task.FromResult(0); #endif /// <summary>Gets a task that's already been completed successfully.</summary> /// <remarks>May not always return the same instance.</remarks> public static Task CompletedTask { get { #if NET451 return _completedTask; #else return Task.CompletedTask; #endif } } } } ``` Change our cached task to a field
```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.Threading.Tasks; namespace Microsoft.AspNetCore.Mvc.Internal { public static class TaskCache { /// <summary> /// A <see cref="Task"/> that's already completed successfully. /// </summary> /// <remarks> /// We're caching this in a static readonly field to make it more inlinable and avoid the volatile lookup done /// by <c>Task.CompletedTask</c>. /// </remarks> #if NET451 public static readonly Task CompletedTask = Task.FromResult(0); #else public static readonly Task CompletedTask = Task.CompletedTask; #endif } } ```
7c56de85-cd65-4664-8a80-36f50b60a8af
{ "language": "C#" }
```c# // Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using ImageMagick; using Xunit; using Xunit.Sdk; namespace Magick.NET.Tests { public partial class ResourceLimitsTests { [Collection(nameof(RunTestsSeparately))] public class TheMaxMemoryRequest { [Fact] public void ShouldHaveTheCorrectValue() { if (ResourceLimits.MaxMemoryRequest < 100000000U) throw new XunitException("Invalid memory limit: " + ResourceLimits.MaxMemoryRequest); } [Fact] public void ShouldReturnTheCorrectValueWhenChanged() { var oldMemory = ResourceLimits.MaxMemoryRequest; var newMemory = (ulong)(ResourceLimits.MaxMemoryRequest * 0.9); ResourceLimits.MaxMemoryRequest = newMemory; Assert.Equal(newMemory, ResourceLimits.MaxMemoryRequest); ResourceLimits.MaxMemoryRequest = oldMemory; } } } } ``` Use different percentage in the unit test.
```c# // Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using ImageMagick; using Xunit; using Xunit.Sdk; namespace Magick.NET.Tests { public partial class ResourceLimitsTests { [Collection(nameof(RunTestsSeparately))] public class TheMaxMemoryRequest { [Fact] public void ShouldHaveTheCorrectValue() { if (ResourceLimits.MaxMemoryRequest < 100000000U) throw new XunitException("Invalid memory limit: " + ResourceLimits.MaxMemoryRequest); } [Fact] public void ShouldReturnTheCorrectValueWhenChanged() { var oldMemory = ResourceLimits.MaxMemoryRequest; var newMemory = (ulong)(ResourceLimits.MaxMemoryRequest * 0.8); ResourceLimits.MaxMemoryRequest = newMemory; Assert.Equal(newMemory, ResourceLimits.MaxMemoryRequest); ResourceLimits.MaxMemoryRequest = oldMemory; } } } } ```
ef367693-89b8-497c-8d60-56e6ad4bb77c
{ "language": "C#" }
```c# using System.Collections.Generic; namespace AttachToolbar { internal static class State { public static string ProcessName = ""; public static List<string> ProcessList = new List<string>(); public static EngineType EngineType = EngineType.Native; public static bool IsAttached = false; public static void Clear() { ProcessList.Clear(); EngineType = EngineType.Native; IsAttached = false; ProcessName = ""; } } } ``` Add process index to state as primary key. Use process name as property
```c# using System.Collections.Generic; namespace AttachToolbar { internal static class State { public static int ProcessIndex = -1; public static List<string> ProcessList = new List<string>(); public static EngineType EngineType = EngineType.Native; public static bool IsAttached = false; public static string ProcessName { get { string processName = ProcessIndex >= 0 ? ProcessList[ProcessIndex] : ""; return processName; } set { ProcessIndex = ProcessList.IndexOf(value); } } public static void Clear() { ProcessList.Clear(); EngineType = EngineType.Native; IsAttached = false; ProcessIndex = -1; } } } ```
7c3b49cb-0aa6-46ac-8dc0-f6848abd95ce
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bloom.Utils { class MemoryUtils { /// <summary> /// A crude way of measuring when we might be short enough of memory to need a full reload. /// </summary> /// <returns></returns> public static bool SystemIsShortOfMemory() { // A rather arbitrary limit of 750M...a bit more than Bloom typically uses for a large book // before memory leaks start to mount up. return GetPrivateBytes() > 750000000; } /// <summary> /// Significance: This counter indicates the current number of bytes allocated to this process that cannot be shared with /// other processes. This counter has been useful for identifying memory leaks. /// </summary> /// <remarks>We've had other versions of this method which, confusingly, returned results in KB. This one actually answers bytes.</remarks> /// <returns></returns> public static long GetPrivateBytes() { using (var perfCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)) { return perfCounter.RawValue; } } } } ``` Fix system memory check for Linux (20210323)
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bloom.Utils { class MemoryUtils { /// <summary> /// A crude way of measuring when we might be short enough of memory to need a full reload. /// </summary> /// <returns></returns> public static bool SystemIsShortOfMemory() { // A rather arbitrary limit of 750M...a bit more than Bloom typically uses for a large book // before memory leaks start to mount up. A larger value is wanted for 64-bit processes // since they can start out above the 750M level. var triggerLevel = Environment.Is64BitProcess ? 2000000000L : 750000000; return GetPrivateBytes() > triggerLevel; } /// <summary> /// Significance: This value indicates the current number of bytes allocated to this process that cannot be shared with /// other processes. This value has been useful for identifying memory leaks. /// </summary> /// <remarks>We've had other versions of this method which, confusingly, returned results in KB. This one actually answers bytes.</remarks> public static long GetPrivateBytes() { // Using a PerformanceCounter does not work on Linux and gains nothing on Windows. // After using the PerformanceCounter once on Windows, it always returns the same // value as getting it directly from the Process property. using (var process = Process.GetCurrentProcess()) { return process.PrivateMemorySize64; } } } } ```
be68c136-0570-408a-ae4f-b86a48cf44ee
{ "language": "C#" }
```c# using System.Collections.Generic; using Amazon.DynamoDBv2.Model; namespace Narochno.Credstash.Internal { public class CredstashItem { public const string DEFAULT_DIGEST = "SHA256"; public string Name { get; set; } public string Version { get; set; } public string Contents { get; set; } public string Digest { get; set; } public string Hmac { get; set; } public string Key { get; set; } public static CredstashItem From(Dictionary<string, AttributeValue> item) { return new CredstashItem { Name = item["name"].S, Version = item["version"].S, Contents = item["contents"].S, Digest = item["digest"]?.S ?? DEFAULT_DIGEST, Hmac = item["hmac"].S, Key = item["key"].S, }; } } }``` Update for Dict contains before null check
```c# using System.Collections.Generic; using Amazon.DynamoDBv2.Model; namespace Narochno.Credstash.Internal { public class CredstashItem { public const string DEFAULT_DIGEST = "SHA256"; public string Name { get; set; } public string Version { get; set; } public string Contents { get; set; } public string Digest { get; set; } public string Hmac { get; set; } public string Key { get; set; } public static CredstashItem From(Dictionary<string, AttributeValue> item) { return new CredstashItem { Name = item["name"].S, Version = item["version"].S, Contents = item["contents"].S, Digest = (item.ContainsKey("digest") ? item["digest"]?.S : null) ?? DEFAULT_DIGEST, Hmac = item["hmac"].S, Key = item["key"].S, }; } } }```
25b10466-521c-4ba7-a6ce-ff9d1afb0226
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.IO; namespace PackageRunner { /// <summary> /// </summary> internal class FileLogging { private readonly string _file; private static readonly object _lock = new object(); public FileLogging(string file) { _file = file; } public void AddLine(string text) { lock (_lock) { File.AppendAllText(_file, DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " " + text); Debug.WriteLine(text); } } /// <summary> /// </summary> public void AddLine(string format, params object[] args) { var text = string.Format(format, args); this.AddLine(text); } } } ``` Add new line for file logging
```c# using System; using System.Diagnostics; using System.IO; namespace PackageRunner { /// <summary> /// </summary> internal class FileLogging { private readonly string _file; private static readonly object _lock = new object(); public FileLogging(string file) { _file = file; } public void AddLine(string text) { lock (_lock) { File.AppendAllText(_file, DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " " + text + Environment.NewLine); Debug.WriteLine(text); } } /// <summary> /// </summary> public void AddLine(string format, params object[] args) { var text = string.Format(format, args); this.AddLine(text); } } } ```
4907f662-fdf4-4e73-9ec3-0c50f996de5f
{ "language": "C#" }
```c# using System; using System.Threading; using Topshelf; namespace Tellurium.VisualAssertion.Dashboard { public class Program { public static void Main(string[] args) { #if DEBUG using (var server = new WebServer()) { server.Run(consoleMode:true); Console.ReadKey(); } #else InstallDashboardService(); #endif } private static void InstallDashboardService() { HostFactory.Run(hostConfiguration => { hostConfiguration.Service<WebServer>(wsc => { wsc.ConstructUsing(() => new WebServer()); wsc.WhenStarted(server => { server.Run(); }); wsc.WhenStopped(ws => ws.Dispose()); }); hostConfiguration.RunAsLocalSystem(); hostConfiguration.SetDescription("This is Tellurium Dashboard"); hostConfiguration.SetDisplayName("Tellurium Dashboard"); hostConfiguration.SetServiceName("TelluriumDashboard"); hostConfiguration.StartAutomatically(); }); } } } ``` Add Debug writer for diagnostic purpose
```c# using System; using System.Diagnostics; using System.IO; using System.Threading; using Topshelf; namespace Tellurium.VisualAssertion.Dashboard { public class Program { public static void Main(string[] args) { #if DEBUG using (var server = new WebServer()) { Console.SetOut(new DebugWriter()); server.Run(consoleMode:true); Console.ReadKey(); } #else InstallDashboardService(); #endif } private static void InstallDashboardService() { HostFactory.Run(hostConfiguration => { hostConfiguration.Service<WebServer>(wsc => { wsc.ConstructUsing(() => new WebServer()); wsc.WhenStarted(server => { server.Run(); }); wsc.WhenStopped(ws => ws.Dispose()); }); hostConfiguration.RunAsLocalSystem(); hostConfiguration.SetDescription("This is Tellurium Dashboard"); hostConfiguration.SetDisplayName("Tellurium Dashboard"); hostConfiguration.SetServiceName("TelluriumDashboard"); hostConfiguration.StartAutomatically(); }); } } public class DebugWriter : StringWriter { public override void WriteLine(string value) { Debug.WriteLine(value); base.WriteLine(value); } } } ```
f27306ae-ca89-4c19-a482-0218ea3c96c2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Baskerville.Models.DataModels { public class ProductCategory { public ProductCategory() { this.Products = new HashSet<Product>(); this.Subcategories = new HashSet<ProductCategory>(); } public int Id { get; set; } public string NameBg { get; set; } public string NameEn { get; set; } public bool IsRemoved { get; set; } public bool IsPrimary { get; set; } public ICollection<Product> Products { get; set; } public ICollection<ProductCategory> Subcategories { get; set; } public int? PrimaryCategoryId { get; set; } public ProductCategory PrimaryCategory { get; set; } } } ``` Add Db validation for ProductCategories model
```c# namespace Baskerville.Models.DataModels { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class ProductCategory { public ProductCategory() { this.Products = new HashSet<Product>(); this.Subcategories = new HashSet<ProductCategory>(); } public int Id { get; set; } [Required] public string NameBg { get; set; } [Required] public string NameEn { get; set; } public bool IsRemoved { get; set; } public bool IsPrimary { get; set; } public ICollection<Product> Products { get; set; } public ICollection<ProductCategory> Subcategories { get; set; } public int? PrimaryCategoryId { get; set; } public ProductCategory PrimaryCategory { get; set; } } }```
d31b3fd9-bd1b-4a10-a041-1ec62530b9df
{ "language": "C#" }
```c# #if FAT namespace Theraot.Threading { public static partial class ThreadingHelper { private static readonly RuntimeUniqueIdProdiver _threadIdProvider = new RuntimeUniqueIdProdiver(); // Leaked until AppDomain unload private static readonly NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId> _threadRuntimeUniqueId = new NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId>(_threadIdProvider.GetNextId); public static bool HasThreadUniqueId { get { return _threadRuntimeUniqueId.IsValueCreated; } } public static RuntimeUniqueIdProdiver.UniqueId ThreadUniqueId { get { return _threadRuntimeUniqueId.Value; } } } } #endif``` Fix - RuntimeUniqueIdProdiver is static
```c# #if FAT namespace Theraot.Threading { public static partial class ThreadingHelper { // Leaked until AppDomain unload private static readonly NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId> _threadRuntimeUniqueId = new NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId>(RuntimeUniqueIdProdiver.GetNextId); public static bool HasThreadUniqueId { get { return _threadRuntimeUniqueId.IsValueCreated; } } public static RuntimeUniqueIdProdiver.UniqueId ThreadUniqueId { get { return _threadRuntimeUniqueId.Value; } } } } #endif```
03a52000-be8a-4d59-81d8-7bce3488cdab
{ "language": "C#" }
```c# using IdentityServer3.Core.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer3.Core.Models; using IdentityServer3.Contrib.RedisStores.Models; using StackExchange.Redis; using IdentityServer3.Contrib.RedisStores.Converters; namespace IdentityServer3.Contrib.RedisStores.Stores { /// <summary> /// /// </summary> public class RefreshTokenStore : RedisTransientStore<RefreshToken, RefreshTokenModel> { /// <summary> /// /// </summary> /// <param name="redis"></param> /// <param name="options"></param> public RefreshTokenStore(IDatabase redis, RedisOptions options) : base(redis, options, new RefreshTokenConverter()) { } /// <summary> /// /// </summary> /// <param name="redis"></param> public RefreshTokenStore(IDatabase redis) : base(redis, new RefreshTokenConverter()) { } internal override string CollectionName => "refreshTokens"; internal override int GetTokenLifetime(RefreshToken token) { return token.LifeTime; } } } ``` Fix namespace and add inheritance
```c# using IdentityServer3.Core.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer3.Core.Models; using IdentityServer3.Contrib.RedisStores.Models; using StackExchange.Redis; using IdentityServer3.Contrib.RedisStores.Converters; namespace IdentityServer3.Contrib.RedisStores { /// <summary> /// /// </summary> public class RefreshTokenStore : RedisTransientStore<RefreshToken, RefreshTokenModel>, IRefreshTokenStore { /// <summary> /// /// </summary> /// <param name="redis"></param> /// <param name="options"></param> public RefreshTokenStore(IDatabase redis, RedisOptions options) : base(redis, options, new RefreshTokenConverter()) { } /// <summary> /// /// </summary> /// <param name="redis"></param> public RefreshTokenStore(IDatabase redis) : base(redis, new RefreshTokenConverter()) { } internal override string CollectionName => "refreshTokens"; internal override int GetTokenLifetime(RefreshToken token) { return token.LifeTime; } } } ```
beb2811e-ffcc-47fb-a7fe-ee164bde2291
{ "language": "C#" }
```c# using AutomaticTypeMapper; using EOLib.Logger; using EOLib.Net; using EOLib.Net.Communication; using EOLib.Net.Handlers; using EOLib.Net.PacketProcessing; namespace EOLib.PacketHandlers { /// <summary> /// Handles incoming CONNECTION_PLAYER packets which are used for updating sequence numbers in the EO protocol /// </summary> [AutoMappedType] public class ConnectionPlayerHandler : DefaultAsyncPacketHandler { private readonly IPacketProcessActions _packetProcessActions; private readonly IPacketSendService _packetSendService; private readonly ILoggerProvider _loggerProvider; public override PacketFamily Family => PacketFamily.Connection; public override PacketAction Action => PacketAction.Player; public override bool CanHandle => true; public ConnectionPlayerHandler(IPacketProcessActions packetProcessActions, IPacketSendService packetSendService, ILoggerProvider loggerProvider) { _packetProcessActions = packetProcessActions; _packetSendService = packetSendService; _loggerProvider = loggerProvider; } public override bool HandlePacket(IPacket packet) { var seq1 = packet.ReadShort(); var seq2 = packet.ReadChar(); _packetProcessActions.SetUpdatedBaseSequenceNumber(seq1, seq2); var response = new PacketBuilder(PacketFamily.Connection, PacketAction.Ping).Build(); try { _packetSendService.SendPacket(response); } catch (NoDataSentException) { return false; } return true; } } } ``` Fix handling of CONNECTION_PLAYER when sending response to GameServer
```c# using AutomaticTypeMapper; using EOLib.Logger; using EOLib.Net; using EOLib.Net.Communication; using EOLib.Net.Handlers; using EOLib.Net.PacketProcessing; namespace EOLib.PacketHandlers { /// <summary> /// Handles incoming CONNECTION_PLAYER packets which are used for updating sequence numbers in the EO protocol /// </summary> [AutoMappedType] public class ConnectionPlayerHandler : DefaultAsyncPacketHandler { private readonly IPacketProcessActions _packetProcessActions; private readonly IPacketSendService _packetSendService; private readonly ILoggerProvider _loggerProvider; public override PacketFamily Family => PacketFamily.Connection; public override PacketAction Action => PacketAction.Player; public override bool CanHandle => true; public ConnectionPlayerHandler(IPacketProcessActions packetProcessActions, IPacketSendService packetSendService, ILoggerProvider loggerProvider) { _packetProcessActions = packetProcessActions; _packetSendService = packetSendService; _loggerProvider = loggerProvider; } public override bool HandlePacket(IPacket packet) { var seq1 = packet.ReadShort(); var seq2 = packet.ReadChar(); _packetProcessActions.SetUpdatedBaseSequenceNumber(seq1, seq2); var response = new PacketBuilder(PacketFamily.Connection, PacketAction.Ping) .AddString("k") .Build(); try { _packetSendService.SendPacket(response); } catch (NoDataSentException) { return false; } return true; } } } ```
bad4b775-8a64-47ac-9b1f-dba9d9b88b0b
{ "language": "C#" }
```c# using System; namespace gdRead.Data.Models { public class Post { public int Id { get; set; } public int FeedId { get; set; } public string Name { get; set; } public string Url { get; set; } public string Summary { get; set; } public string Content { get; set; } public DateTime PublishDate { get; set; } public bool Read { get; set; } public DateTime DateFetched { get;set; } public Post() { DateFetched = DateTime.Now; } } } ``` Fix issue where Dapper was trying to insert Read into the post table where that column doesnt exist
```c# using System; using DapperExtensions.Mapper; namespace gdRead.Data.Models { public class Post { public int Id { get; set; } public int FeedId { get; set; } public string Name { get; set; } public string Url { get; set; } public string Summary { get; set; } public string Content { get; set; } public DateTime PublishDate { get; set; } public bool Read { get; set; } public DateTime DateFetched { get;set; } public Post() { DateFetched = DateTime.Now; } } public class PostMapper : ClassMapper<Post> { public PostMapper() { Table("Post"); Map(m => m.Read).Ignore(); AutoMap(); } } } ```
42835f21-74f8-4459-b0b6-161258b5074d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.ManagedDialogs { internal class ManagedFileChooserFilterViewModel : ViewModelBase { private readonly string[] Extensions; public string Name { get; } public ManagedFileChooserFilterViewModel(FileDialogFilter filter) { Name = filter.Name; if (filter.Extensions.Contains("*")) { return; } Extensions = filter.Extensions?.Select(e => "." + e.ToLowerInvariant()).ToArray(); } public ManagedFileChooserFilterViewModel() { Name = "All files"; } public bool Match(string filename) { if (Extensions is null) { return true; } foreach (var ext in Extensions) { if (filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase)) { return true; } } return false; } public override string ToString() => Name; } } ``` Replace string[] field by IEnumerable<string> property
```c# using System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.ManagedDialogs { internal class ManagedFileChooserFilterViewModel : ViewModelBase { private IEnumerable<string> Extensions { get; } public string Name { get; } public ManagedFileChooserFilterViewModel(FileDialogFilter filter) { Name = filter.Name; if (filter.Extensions.Contains("*")) { return; } Extensions = filter.Extensions?.Select(e => "." + e.ToLowerInvariant()); } public ManagedFileChooserFilterViewModel() { Name = "All files"; } public bool Match(string filename) { if (Extensions is null) { return true; } foreach (var ext in Extensions) { if (filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase)) { return true; } } return false; } public override string ToString() => Name; } } ```
406ff2f4-7466-4a1c-be48-1db54c3efe12
{ "language": "C#" }
```c# // Copyright (c) 2015 Eberhard Beilharz // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("BuildDependencyTestApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2014-2016 Eberhard Beilharz")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] ``` Use GitVersion for test app
```c# // Copyright (c) 2015 Eberhard Beilharz // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("BuildDependencyTestApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2014-2017 Eberhard Beilharz")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] ```
6905c007-7c0e-4b39-93d5-8d43019fe750
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DotVVM.Framework.Compilation.Binding { public class DefaultExtensionsProvider : IExtensionsProvider { private readonly List<Type> typesLookup; public DefaultExtensionsProvider() { typesLookup = new List<Type>(); AddTypeForExtensionsLookup(typeof(Enumerable)); } protected void AddTypeForExtensionsLookup(Type type) { typesLookup.Add(typeof(Enumerable)); } public virtual IEnumerable<MethodInfo> GetExtensionMethods() { foreach (var registeredType in typesLookup) foreach (var method in registeredType.GetMethods(BindingFlags.Public | BindingFlags.Static)) yield return method; } } } ``` Fix issue when adding type to ExtensionsProvider
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DotVVM.Framework.Compilation.Binding { public class DefaultExtensionsProvider : IExtensionsProvider { private readonly List<Type> typesLookup; public DefaultExtensionsProvider() { typesLookup = new List<Type>(); AddTypeForExtensionsLookup(typeof(Enumerable)); } protected void AddTypeForExtensionsLookup(Type type) { typesLookup.Add(type); } public virtual IEnumerable<MethodInfo> GetExtensionMethods() { foreach (var registeredType in typesLookup) foreach (var method in registeredType.GetMethods(BindingFlags.Public | BindingFlags.Static)) yield return method; } } } ```
2f6fb05b-f40f-46b5-8cee-3ebbbb80d861
{ "language": "C#" }
```c# // project created on 11.11.2001 at 15:19 using System; using System.IO; using ICSharpCode.SharpZipLib.GZip; class MainClass { public static void Main(string[] args) { if (args[0] == "-d") { // decompress Stream s = new GZipInputStream(File.OpenRead(args[1])); FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1])); int size = 2048; byte[] writeData = new byte[2048]; while (true) { size = s.Read(writeData, 0, size); if (size > 0) { fs.Write(writeData, 0, size); } else { break; } } s.Close(); } else { // compress Stream s = new GZipOutputStream(File.Create(args[0] + ".gz")); FileStream fs = File.OpenRead(args[0]); byte[] writeData = new byte[fs.Length]; fs.Read(writeData, 0, (int)fs.Length); s.Write(writeData, 0, writeData.Length); s.Close(); } } } ``` Stop exception when no argument sare suppplied to minigzip
```c# // project created on 11.11.2001 at 15:19 using System; using System.IO; using ICSharpCode.SharpZipLib.GZip; class MainClass { public static void Main(string[] args) { if ( args.Length > 0 ) { if ( args[0] == "-d" ) { // decompress Stream s = new GZipInputStream(File.OpenRead(args[1])); FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1])); int size = 2048; byte[] writeData = new byte[2048]; while (true) { size = s.Read(writeData, 0, size); if (size > 0) { fs.Write(writeData, 0, size); } else { break; } } s.Close(); } else { // compress Stream s = new GZipOutputStream(File.Create(args[0] + ".gz")); FileStream fs = File.OpenRead(args[0]); byte[] writeData = new byte[fs.Length]; fs.Read(writeData, 0, (int)fs.Length); s.Write(writeData, 0, writeData.Length); s.Close(); } } } } ```
be36e30f-482a-4d5a-b069-b6a02d300ad6
{ "language": "C#" }
```c# using System; using System.IO; using System.Reflection; // ReSharper disable once CheckNamespace internal static class Program { private static int Main(string[] args) { // Mono's XBuild uses assembly redirects to make sure it uses .NET 4.5 target binaries. // We emulate it using our own assembly redirector. AppDomain.CurrentDomain.AssemblyLoad += (sender, e) => { var assemblyName = e.LoadedAssembly.GetName(); Console.WriteLine("Assembly load: {0}", assemblyName); }; var mainAsm = Assembly.Load("citizenmp_server_updater"); mainAsm.GetType("Costura.AssemblyLoader") .GetMethod("Attach") .Invoke(null, null); return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program") .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static) .Invoke(null, new object[] {args}); } }``` Remove assembly load debug lines.
```c# using System; using System.IO; using System.Reflection; // ReSharper disable once CheckNamespace internal static class Program { private static int Main(string[] args) { var mainAsm = Assembly.Load("citizenmp_server_updater"); mainAsm.GetType("Costura.AssemblyLoader") .GetMethod("Attach") .Invoke(null, null); return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program") .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static) .Invoke(null, new object[] {args}); } }```
4a4728be-dcf1-450f-ac5f-70b7d528c03a
{ "language": "C#" }
```c# using Microsoft.VisualStudio.TestTools.UnitTesting; using SaurusConsole.OthelloAI; namespace SaurusConsoleTests { [TestClass] public class MoveTests { [TestMethod] public void NotationConstuctorTest() { Move e4move = new Move("E4"); Assert.AreEqual("E4", e4move.ToString()); Move a1move = new Move("A1"); Assert.AreEqual("A1", a1move.ToString()); Move a8move = new Move("A8"); Assert.AreEqual("A8", a8move.ToString()); Move h1move = new Move("H1"); Assert.AreEqual("H1", h1move.ToString()); Move h8move = new Move("H8"); Assert.AreEqual("H8", h8move.ToString()); } [TestMethod] public void ToStringTest() { ulong h1Mask = 1; Move h1Move = new Move(h1Mask); Assert.AreEqual("H1", h1Move.ToString()); ulong e4Mask = 0x8000000; Move e4Move = new Move(e4Mask); Assert.AreEqual("E4", e4Move.ToString()); } [TestMethod] public void GetBitMaskTest() { ulong mask = 0b1000000000000; Move move = new Move(mask); Assert.AreEqual(mask, move.GetBitMask()); } } } ``` Test if a failed test will fail the build
```c# using Microsoft.VisualStudio.TestTools.UnitTesting; using SaurusConsole.OthelloAI; namespace SaurusConsoleTests { [TestClass] public class MoveTests { [TestMethod] public void NotationConstuctorTest() { Move e4move = new Move("E4"); Assert.AreEqual("E4", e4move.ToString()); Move a1move = new Move("A1"); Assert.AreEqual("A1", a1move.ToString()); Move a8move = new Move("A8"); Assert.AreEqual("A8", a8move.ToString()); Move h1move = new Move("H1"); Assert.AreEqual("H1", h1move.ToString()); Move h8move = new Move("H8"); Assert.AreEqual("H8", h8move.ToString()); Assert.Fail(); } [TestMethod] public void ToStringTest() { ulong h1Mask = 1; Move h1Move = new Move(h1Mask); Assert.AreEqual("H1", h1Move.ToString()); ulong e4Mask = 0x8000000; Move e4Move = new Move(e4Mask); Assert.AreEqual("E4", e4Move.ToString()); } [TestMethod] public void GetBitMaskTest() { ulong mask = 0b1000000000000; Move move = new Move(mask); Assert.AreEqual(mask, move.GetBitMask()); } } } ```
b12ebf43-b617-4c97-9b40-4ad8c3860dc4
{ "language": "C#" }
```c# using System.Diagnostics; using System.IO; using Hangfire; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.HttpSys; using SupportManager.Contracts; using Topshelf; namespace SupportManager.Web { public class Program { private static string[] args; public static void Main() { HostFactory.Run(cfg => { cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' ')); cfg.SetServiceName("SupportManager.Web"); cfg.SetDisplayName("SupportManager.Web"); cfg.SetDescription("SupportManager Web Interface"); cfg.Service<IWebHost>(svc => { svc.ConstructUsing(CreateWebHost); svc.WhenStarted(webHost => { webHost.Start(); RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.Minutely); }); svc.WhenStopped(webHost => webHost.Dispose()); }); cfg.RunAsLocalSystem(); cfg.StartAutomatically(); }); } private static IWebHost CreateWebHost() { var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>(); if (!Debugger.IsAttached) { builder.UseHttpSys(options => { options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate; options.Authentication.AllowAnonymous = true; }); builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)); } return builder.Build(); } } } ``` Set interval to 10 minutes
```c# using System.Diagnostics; using System.IO; using Hangfire; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.HttpSys; using SupportManager.Contracts; using Topshelf; namespace SupportManager.Web { public class Program { private static string[] args; public static void Main() { HostFactory.Run(cfg => { cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' ')); cfg.SetServiceName("SupportManager.Web"); cfg.SetDisplayName("SupportManager.Web"); cfg.SetDescription("SupportManager Web Interface"); cfg.Service<IWebHost>(svc => { svc.ConstructUsing(CreateWebHost); svc.WhenStarted(webHost => { webHost.Start(); RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.MinuteInterval(10)); }); svc.WhenStopped(webHost => webHost.Dispose()); }); cfg.RunAsLocalSystem(); cfg.StartAutomatically(); }); } private static IWebHost CreateWebHost() { var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>(); if (!Debugger.IsAttached) { builder.UseHttpSys(options => { options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate; options.Authentication.AllowAnonymous = true; }); builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)); } return builder.Build(); } } } ```
e857029b-5a7b-43ee-9639-7dab0e2f5651
{ "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 Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace Nether.Web.Features.Identity { [Route("identity-test")] [Authorize] public class IdentityTestController : ControllerBase { [HttpGet] public IActionResult Get() { return new JsonResult(from c in User.Claims select new { c.Type, c.Value }); } } } ``` Make identity-test API easier to consume
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace Nether.Web.Features.Identity { [Route("identity-test")] [Authorize] public class IdentityTestController : ControllerBase { [HttpGet] public IActionResult Get() { // Convert claim type, value pairs into a dictionary for easier consumption as JSON // Need to group as there can be multiple claims of the same type (e.g. 'scope') var result = User.Claims .GroupBy(c => c.Type) .ToDictionary( keySelector: g => g.Key, elementSelector: g => g.Count() == 1 ? (object)g.First().Value : g.Select(t => t.Value).ToArray() ); return new JsonResult(result); } } } ```
9b45006f-1ffd-4675-85a0-ce4c39c3c4de
{ "language": "C#" }
```c# /* * The official C# API client for alpaca brokerage * Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/tree/v3.0.2 */ using System; using Newtonsoft.Json; namespace QuantConnect.Brokerages.Alpaca.Markets { internal sealed class JsonError { [JsonProperty(PropertyName = "code", Required = Required.Always)] public Int32 Code { get; set; } [JsonProperty(PropertyName = "message", Required = Required.Always)] public String Message { get; set; } } } ``` Fix Alpaca error message deserialization
```c# /* * The official C# API client for alpaca brokerage * Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/tree/v3.0.2 */ using System; using Newtonsoft.Json; namespace QuantConnect.Brokerages.Alpaca.Markets { internal sealed class JsonError { [JsonProperty(PropertyName = "code", Required = Required.Default)] public Int32 Code { get; set; } [JsonProperty(PropertyName = "message", Required = Required.Always)] public String Message { get; set; } } } ```
264bc289-baaa-413b-b391-9ec9e1025464
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using osu.Game.Users; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser> { public readonly long UserID; public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle; public User? User { get; set; } public MultiplayerRoomUser(in int userId) { UserID = userId; } public bool Equals(MultiplayerRoomUser other) { if (ReferenceEquals(this, other)) return true; return UserID == other.UserID; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((MultiplayerRoomUser)obj); } public override int GetHashCode() => UserID.GetHashCode(); } } ``` Change user id type to int
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using osu.Game.Users; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser> { public readonly int UserID; public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle; public User? User { get; set; } public MultiplayerRoomUser(in int userId) { UserID = userId; } public bool Equals(MultiplayerRoomUser other) { if (ReferenceEquals(this, other)) return true; return UserID == other.UserID; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((MultiplayerRoomUser)obj); } public override int GetHashCode() => UserID.GetHashCode(); } } ```
7774f76a-8ea1-4b99-8296-99264275c463
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace IvionSoft { public class History<T> { public int Length { get; private set; } HashSet<T> hashes; Queue<T> queue; object _locker = new object(); public History(int length) : this(length, null) {} public History(int length, IEqualityComparer<T> comparer) { if (length < 1) throw new ArgumentException("Must be 1 or larger", "length"); Length = length; queue = new Queue<T>(length + 1); if (comparer != null) hashes = new HashSet<T>(comparer); else hashes = new HashSet<T>(); } public bool Contains(T item) { return hashes.Contains(item); } public bool Add(T item) { bool added; lock (_locker) { added = hashes.Add(item); if (added) { queue.Enqueue(item); if (queue.Count > Length) { T toRemove = queue.Dequeue(); hashes.Remove(toRemove); } } } return added; } } }``` Remove locking code and make it possible to have a dummy history, by calling the parameterless constructor.
```c# using System; using System.Collections.Generic; namespace IvionSoft { public class History<T> { public int Length { get; private set; } HashSet<T> hashes; Queue<T> queue; public History() { Length = 0; } public History(int length) : this(length, null) {} public History(int length, IEqualityComparer<T> comparer) { if (length < 1) throw new ArgumentException("Cannot be less than or equal to 0.", "length"); Length = length; queue = new Queue<T>(length + 1); if (comparer != null) hashes = new HashSet<T>(comparer); else hashes = new HashSet<T>(); } public bool Contains(T item) { if (Length > 0) return hashes.Contains(item); else return false; } public bool Add(T item) { if (Length == 0) return false; bool added; added = hashes.Add(item); if (added) { queue.Enqueue(item); if (queue.Count > Length) { T toRemove = queue.Dequeue(); hashes.Remove(toRemove); } } return added; } } }```
0965842a-4559-4c0e-8d43-4674242169df
{ "language": "C#" }
```c# using System; using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that compare the module of definition. /// </summary> public class ModuleFunction : PatternFunction { internal const string FnName = "module"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is IOwnerModule)) return false; object name = Arguments[0].Evaluate(definition); return ((IOwnerModule)definition).Module.Name == name.ToString(); } } }``` Support module def in module function
```c# using System; using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that compare the module of definition. /// </summary> public class ModuleFunction : PatternFunction { internal const string FnName = "module"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is IOwnerModule) && !(definition is IModule)) return false; object name = Arguments[0].Evaluate(definition); if (definition is IModule) return ((IModule)definition).Name == name.ToString(); return ((IOwnerModule)definition).Module.Name == name.ToString(); } } }```
273ff277-f05c-4118-b3f1-d2a1946ccdfb
{ "language": "C#" }
```c# using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Stampsy.ImageSource { public class FileDestination : IDestination<FileRequest> { public string Folder { get; private set; } public FileDestination (string folder) { Folder = folder; } public FileRequest CreateRequest (IDescription description) { var url = description.Url; var filename = ComputeHash (url) + description.Extension; return new FileRequest (description) { Filename = Path.Combine (Folder, filename) }; } static string ComputeHash (Uri url) { string hash; using (var sha1 = new SHA1CryptoServiceProvider ()) { var bytes = Encoding.ASCII.GetBytes (url.ToString ()); hash = BitConverter.ToString (sha1.ComputeHash (bytes)); } return hash.Replace ("-", string.Empty).ToLower (); } } } ``` Add helpers for saving in Library and Library/Caches
```c# using System; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Stampsy.ImageSource { public class FileDestination : IDestination<FileRequest> { public static FileDestination InLibrary (params string [] folders) { var folder = Path.Combine (new [] { "..", "Library" }.Concat (folders).ToArray ()); Directory.CreateDirectory (folder); return new FileDestination (folder); } public static FileDestination InLibraryCaches (params string [] folders) { return InLibrary (new [] { "Caches" }.Concat (folders).ToArray ()); } public string Folder { get; private set; } public FileDestination (string folder) { Folder = folder; } public FileRequest CreateRequest (IDescription description) { var url = description.Url; var filename = ComputeHash (url) + description.Extension; return new FileRequest (description) { Filename = Path.Combine (Folder, filename) }; } static string ComputeHash (Uri url) { string hash; using (var sha1 = new SHA1CryptoServiceProvider ()) { var bytes = Encoding.ASCII.GetBytes (url.ToString ()); hash = BitConverter.ToString (sha1.ComputeHash (bytes)); } return hash.Replace ("-", string.Empty).ToLower (); } } } ```
79d4b27f-a9e3-4f56-862e-3e27bd1598e4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace Simple.Domain.Model { public class Organization { public Guid Id { get; set; } public string Name { get; set; } public string CatchPhrase { get; set; } public string BSPhrase { get; set; } // Ref public DomainUser Owner { get; set; } // List Ref public List<Address> Addresses { get; set; } public List<DomainUser> Employees { get; set; } } }``` Update to use new User
```c# using System; using System.Collections.Generic; using Simple.Domain.Entities; namespace Simple.Domain.Model { public class Organization { public Guid Id { get; set; } public string Name { get; set; } public string CatchPhrase { get; set; } public string BSPhrase { get; set; } // Ref public User Owner { get; set; } // List Ref public List<Address> Addresses { get; set; } public List<User> Employees { get; set; } } }```
fd3ace4a-fd5f-46b1-9940-1511210460d2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicCash { /// <summary> /// The customer /// </summary> public class Alice : BaseActor { } } ``` Add some helpers and stuff
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicCash { /// <summary> /// The customer /// </summary> public class Alice : BaseActor { public List<MoneyOrder> MoneyOrders { get; private set; } public string PersonalData { get; private set; } public byte[] PersonalDataBytes { get; private set; } public Alice(string _name, Guid _actorGuid, string _personalData) { Name = _name; ActorGuid = _actorGuid; Money = 1000; PersonalData = _personalData; PersonalDataBytes = GetBytes(_personalData); } /// <summary> /// Called every time the customer wants to pay for something /// </summary> public void CreateMoneyOrders() { MoneyOrders = new List<MoneyOrder>(); } #region private methods /// <summary> /// stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte /// </summary> /// <param name="str"></param> /// <returns></returns> private static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } /// <summary> /// stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte /// </summary> /// <param name="bytes"></param> /// <returns></returns> private static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } #endregion } } ```
93246fd9-dcdf-426d-9eea-c9e0e5d94a13
{ "language": "C#" }
```c# // Copyright 2015 Palm Stone Games, Inc. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class ue4czmq : ModuleRules { public ue4czmq(TargetInfo Target) { // Include paths //PublicIncludePaths.AddRange(new string[] {}); //PrivateIncludePaths.AddRange(new string[] {}); // Dependencies PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", }); //PrivateDependencyModuleNames.AddRange(new string[] {}); // Dynamically loaded modules //DynamicallyLoadedModuleNames.AddRange(new string[] {}); // Definitions Definitions.Add("WITH_UE4CZMQ=1"); LoadLib(Target); } public void LoadLib(TargetInfo Target) { string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); // CZMQ string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq")); PrivateAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib")); PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes")); // LIBZMQ string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq")); PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes")); } } }``` Revert "Use a PrivateAdditionalLibrary for czmq.lib instead of a public one"
```c# // Copyright 2015 Palm Stone Games, Inc. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class ue4czmq : ModuleRules { public ue4czmq(TargetInfo Target) { // Include paths //PublicIncludePaths.AddRange(new string[] {}); //PrivateIncludePaths.AddRange(new string[] {}); // Dependencies PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", }); //PrivateDependencyModuleNames.AddRange(new string[] {}); // Dynamically loaded modules //DynamicallyLoadedModuleNames.AddRange(new string[] {}); // Definitions Definitions.Add("WITH_UE4CZMQ=1"); LoadLib(Target); } public void LoadLib(TargetInfo Target) { string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); // CZMQ string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq")); PublicAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib")); PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes")); // LIBZMQ string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq")); PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes")); } } }```
068778a1-ff3d-4698-907c-9f2d86ba3312
{ "language": "C#" }
```c# @model APFT @using (Html.BeginForm("Edit", "APFT", FormMethod.Post, new { @class = "form-horizontal" role = "form" })) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Id) @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Soldier) @Html.EditorFor(model => model.SoldierId) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Date) @Html.EditorFor(model => model.Date) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.PushUps) @Html.EditorFor(model => model.PushUps) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.SitUps) @Html.EditorFor(model => model.SitUps) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Run) @Html.EditorFor(model => model.Run) </div> <button type="submit">Save</button> }``` Make soldier a dropdown list
```c# @model APFT @using (Html.BeginForm("Edit", "APFT", FormMethod.Post, new { @class = "form-horizontal" role = "form" })) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Id) @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Soldier) @Html.DropDownListFor(model => model.SoldierId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --") </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Date) @Html.EditorFor(model => model.Date) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.PushUps) @Html.EditorFor(model => model.PushUps) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.SitUps) @Html.EditorFor(model => model.SitUps) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Run) @Html.EditorFor(model => model.Run) </div> <button type="submit">Save</button> }```
8d3d4c25-49f4-4c41-b440-e27a8816f88c
{ "language": "C#" }
```c# #region copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="SimpleTests.cs" company="Stephen Reindl"> // Copyright (c) Stephen Reindl. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // </copyright> // <summary> // Part of oberon0 - Oberon0Compiler.Tests/SimpleTests.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace Oberon0.Compiler.Tests { using NUnit.Framework; using Oberon0.Compiler.Definitions; using Oberon0.TestSupport; [TestFixture] public class SimpleTests { [Test] public void EmptyApplication() { Module m = Oberon0Compiler.CompileString("MODULE Test; END Test."); Assert.AreEqual("Test", m.Name); Assert.AreEqual(2, m.Block.Declarations.Count); } [Test] public void EmptyApplication2() { Module m = TestHelper.CompileString( @"MODULE Test; BEGIN END Test."); Assert.AreEqual(0, m.Block.Statements.Count); } [Test] public void ModuleMissingDot() { TestHelper.CompileString( @"MODULE Test; END Test", "missing '.' at '<EOF>'"); } [Test] public void ModuleMissingId() { TestHelper.CompileString( @"MODULE ; BEGIN END Test.", "missing ID at ';'", "The name of the module does not match the end node"); } } }``` Update unit test error for new const
```c# #region copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="SimpleTests.cs" company="Stephen Reindl"> // Copyright (c) Stephen Reindl. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // </copyright> // <summary> // Part of oberon0 - Oberon0Compiler.Tests/SimpleTests.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace Oberon0.Compiler.Tests { using NUnit.Framework; using Oberon0.Compiler.Definitions; using Oberon0.TestSupport; [TestFixture] public class SimpleTests { [Test] public void EmptyApplication() { Module m = Oberon0Compiler.CompileString("MODULE Test; END Test."); Assert.AreEqual("Test", m.Name); Assert.AreEqual(3, m.Block.Declarations.Count); } [Test] public void EmptyApplication2() { Module m = TestHelper.CompileString( @"MODULE Test; BEGIN END Test."); Assert.AreEqual(0, m.Block.Statements.Count); } [Test] public void ModuleMissingDot() { TestHelper.CompileString( @"MODULE Test; END Test", "missing '.' at '<EOF>'"); } [Test] public void ModuleMissingId() { TestHelper.CompileString( @"MODULE ; BEGIN END Test.", "missing ID at ';'", "The name of the module does not match the end node"); } } }```
3600283a-bd12-4dcd-9e0e-e6c5f15c5b5a
{ "language": "C#" }
```c# namespace MvvmFx.CaliburnMicro { using System; /// <summary> /// Used to manage logging. /// </summary> public static class LogManager { private static readonly Logging.ILog NullLogInstance = new Logging.NullLogger(); /// <summary> /// Creates an <see cref="Logging.ILog"/> for the provided type. /// </summary> public static Func<Type, Logging.ILog> GetLog = type => NullLogInstance; } }``` Disable warning "Type is not CLS-compliant"
```c# namespace MvvmFx.CaliburnMicro { using System; /// <summary> /// Used to manage logging. /// </summary> public static class LogManager { private static readonly Logging.ILog NullLogInstance = new Logging.NullLogger(); #pragma warning disable CS3003 // Type is not CLS-compliant /// <summary> /// Creates an <see cref="Logging.ILog"/> for the provided type. /// </summary> public static Func<Type, Logging.ILog> GetLog = type => NullLogInstance; #pragma warning restore CS3003 // Type is not CLS-compliant } }```
07efee9e-69b2-44fe-8e4d-b9ba86165712
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CsQuery.Implementation { public class TrueStringComparer : IComparer<string>, IEqualityComparer<string> { public int Compare(string x, string y) { int pos = 0; int len = Math.Min(x.Length, y.Length); while (pos < len) { var xi = (int)x[pos]; var yi = (int)y[pos]; if (xi < yi) { return -1; } else if (yi < xi) { return 1; } pos++; } if (x.Length < y.Length) { return -1; } else if (y.Length < x.Length) { return 1; } else { return 0; } } public bool Equals(string x, string y) { return Compare(x, y) == 0; } public int GetHashCode(string obj) { return obj.GetHashCode(); } } } ``` Use custom string comparer for RangeSortedDictionary
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CsQuery.Implementation { public class TrueStringComparer : IComparer<string>, IEqualityComparer<string> { public int Compare(string x, string y) { int pos = 0; int len = Math.Min(x.Length, y.Length); while (pos < len) { var xi = (int)x[pos]; var yi = (int)y[pos]; if (xi < yi) { return -1; } else if (yi < xi) { return 1; } pos++; } if (x.Length < y.Length) { return -1; } else if (y.Length < x.Length) { return 1; } else { return 0; } } public bool Equals(string x, string y) { return x.Length == y.Length && Compare(x, y) == 0; } public int GetHashCode(string obj) { return obj.GetHashCode(); } } } ```
4c8e5d8c-635a-429f-af3f-b9872981fb3a
{ "language": "C#" }
```c# using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace Sakuno.Collections { [EditorBrowsable(EditorBrowsableState.Never)] public static class EnumerableExtensions { public static bool AnyNull<T>(this IEnumerable<T> source) where T : class { foreach (var item in source) if (item == null) return true; return false; } public static IEnumerable<TSource> NotOfType<TSource, TExclusion>(this IEnumerable<TSource> source) { foreach (var item in source) { if (item is TExclusion) continue; yield return item; } } public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> source) => source.OrderBy(IdentityFunction<T>.Instance); public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> items, IComparer<T> comparer) => items.OrderBy(IdentityFunction<T>.Instance, comparer); public static IEnumerable<(T, bool)> EnumerateItemAndIfIsLast<T>(this IEnumerable<T> items) { using (var enumerator = items.GetEnumerator()) { var last = default(T); if (!enumerator.MoveNext()) yield break; var shouldYield = false; do { if (shouldYield) yield return (last, false); shouldYield = true; last = enumerator.Current; } while (enumerator.MoveNext()); yield return (last, true); } } } } ``` Add field names in returned tuple of EnumerateItemAndIfIsLast()
```c# using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace Sakuno.Collections { [EditorBrowsable(EditorBrowsableState.Never)] public static class EnumerableExtensions { public static bool AnyNull<T>(this IEnumerable<T> source) where T : class { foreach (var item in source) if (item == null) return true; return false; } public static IEnumerable<TSource> NotOfType<TSource, TExclusion>(this IEnumerable<TSource> source) { foreach (var item in source) { if (item is TExclusion) continue; yield return item; } } public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> source) => source.OrderBy(IdentityFunction<T>.Instance); public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> items, IComparer<T> comparer) => items.OrderBy(IdentityFunction<T>.Instance, comparer); public static IEnumerable<(T Item, bool IsLast)> EnumerateItemAndIfIsLast<T>(this IEnumerable<T> items) { using (var enumerator = items.GetEnumerator()) { var last = default(T); if (!enumerator.MoveNext()) yield break; var shouldYield = false; do { if (shouldYield) yield return (last, false); shouldYield = true; last = enumerator.Current; } while (enumerator.MoveNext()); yield return (last, true); } } } } ```
f0597702-c6a2-46e6-abe9-32c305ab8981
{ "language": "C#" }
```c# namespace OpenRealEstate.Services { public interface ITransmorgrifier { /// <summary> /// Converts some given data into a listing instance. /// </summary> /// <param name="data">some data source, like Xml data or json data.</param> /// <param name="isClearAllIsModified">After the data is loaded, do we clear all IsModified fields so it looks like the listing(s) are all ready to be used and/or compared against other listings.</param> /// <param name="areBadCharactersRemoved">Help clean up the data.</param> /// <returns>List of listings and any unhandled data.</returns> /// <remarks>Why does <code>isClearAllIsModified</code> default to <code>false</code>? Because when you generally load some data into a new listing instance, you want to see which properties </remarks> ConvertToResult ConvertTo(string data, bool isClearAllIsModified = false, bool areBadCharactersRemoved = false); } }``` Correct ordering of method arguments.
```c# namespace OpenRealEstate.Services { public interface ITransmorgrifier { /// <summary> /// Converts some given data into a listing instance. /// </summary> /// <param name="data">some data source, like Xml data or json data.</param> /// <param name="areBadCharactersRemoved">Help clean up the data.</param> /// <param name="isClearAllIsModified">After the data is loaded, do we clear all IsModified fields so it looks like the listing(s) are all ready to be used and/or compared against other listings.</param> /// <returns>List of listings and any unhandled data.</returns> /// <remarks>Why does <code>isClearAllIsModified</code> default to <code>false</code>? Because when you generally load some data into a new listing instance, you want to see which properties </remarks> ConvertToResult ConvertTo(string data, bool areBadCharactersRemoved = false, bool isClearAllIsModified = false); } }```
d0287261-5633-49c6-822e-f50acfadb58a
{ "language": "C#" }
```c# // Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace Core2D.Avalonia { public class MainWindow : Window { public MainWindow() { this.InitializeComponent(); this.AttachDevTools(); Renderer.DrawDirtyRects = true; Renderer.DrawFps = true; } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } } ``` Enable only in debug mode
```c# // Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace Core2D.Avalonia { public class MainWindow : Window { public MainWindow() { this.InitializeComponent(); this.AttachDevTools(); #if DEBUG Renderer.DrawDirtyRects = true; Renderer.DrawFps = true; #endif } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } } ```
05960004-6309-4215-8d98-14769af55664
{ "language": "C#" }
```c# using LiteNetLib; using System; namespace LiteNetLibManager { [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public class SyncFieldAttribute : Attribute { /// <summary> /// Sending method type /// </summary> public DeliveryMethod deliveryMethod; /// <summary> /// Interval to send network data (0.01f to 2f) /// </summary> public float sendInterval = 0.1f; /// <summary> /// If this is `TRUE` it will syncing although no changes /// </summary> public bool alwaysSync; /// <summary> /// If this is `TRUE` it will not sync initial data immdediately with spawn message (it will sync later) /// </summary> public bool doNotSyncInitialDataImmediately; /// <summary> /// How data changes handle and sync /// </summary> public LiteNetLibSyncField.SyncMode syncMode; /// <summary> /// Function name which will be invoked when data changed /// </summary> public string hook; } } ``` Set default values to sync field attribute
```c# using LiteNetLib; using System; namespace LiteNetLibManager { [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public class SyncFieldAttribute : Attribute { /// <summary> /// Sending method type /// </summary> public DeliveryMethod deliveryMethod = DeliveryMethod.ReliableOrdered; /// <summary> /// Interval to send network data (0.01f to 2f) /// </summary> public float sendInterval = 0.1f; /// <summary> /// If this is `TRUE` it will syncing although no changes /// </summary> public bool alwaysSync = false; /// <summary> /// If this is `TRUE` it will not sync initial data immdediately with spawn message (it will sync later) /// </summary> public bool doNotSyncInitialDataImmediately = false; /// <summary> /// How data changes handle and sync /// </summary> public LiteNetLibSyncField.SyncMode syncMode = LiteNetLibSyncField.SyncMode.ServerToClients; /// <summary> /// Function name which will be invoked when data changed /// </summary> public string hook = string.Empty; } } ```
33b7cae0-240d-4755-8ab0-fef706041ed4
{ "language": "C#" }
```c# using System; using Microsoft.EntityFrameworkCore.Migrations; using System.IO; namespace osu.Game.Migrations { public partial class StandardizePaths : Migration { protected override void Up(MigrationBuilder migrationBuilder) { string sanitized = Path.DirectorySeparatorChar.ToString(); string standardized = "/"; // Escaping \ does not seem to be needed. migrationBuilder.Sql($"UPDATE `BeatmapInfo` SET `Path` = REPLACE(`Path`, '{sanitized}', '{standardized}')"); migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `AudioFile` = REPLACE(`AudioFile`, '{sanitized}', '{standardized}')"); migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `BackgroundFile` = REPLACE(`BackgroundFile`, '{sanitized}', '{standardized}')"); migrationBuilder.Sql($"UPDATE `BeatmapSetFileInfo` SET `Filename` = REPLACE(`Filename`, '{sanitized}', '{standardized}')"); migrationBuilder.Sql($"UPDATE `SkinFileInfo` SET `Filename` = REPLACE(`Filename`, '{sanitized}', '{standardized}')"); } protected override void Down(MigrationBuilder migrationBuilder) { } } } ``` Fix Windows-style path separators not being migrated on Unix systems
```c# using System; using Microsoft.EntityFrameworkCore.Migrations; using System.IO; namespace osu.Game.Migrations { public partial class StandardizePaths : Migration { protected override void Up(MigrationBuilder migrationBuilder) { string windowsStyle = @"\"; string standardized = "/"; // Escaping \ does not seem to be needed. migrationBuilder.Sql($"UPDATE `BeatmapInfo` SET `Path` = REPLACE(`Path`, '{windowsStyle}', '{standardized}')"); migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `AudioFile` = REPLACE(`AudioFile`, '{windowsStyle}', '{standardized}')"); migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `BackgroundFile` = REPLACE(`BackgroundFile`, '{windowsStyle}', '{standardized}')"); migrationBuilder.Sql($"UPDATE `BeatmapSetFileInfo` SET `Filename` = REPLACE(`Filename`, '{windowsStyle}', '{standardized}')"); migrationBuilder.Sql($"UPDATE `SkinFileInfo` SET `Filename` = REPLACE(`Filename`, '{windowsStyle}', '{standardized}')"); } protected override void Down(MigrationBuilder migrationBuilder) { } } } ```
707d37d0-140a-4648-804f-58366f596518
{ "language": "C#" }
```c# // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo.Applicative { using System; using Narvalo; // Query Expression Pattern for nullables. public static class Qullable { public static TResult? Select<TSource, TResult>(this TSource? @this, Func<TSource, TResult> selector) where TSource : struct where TResult : struct { Require.NotNull(selector, nameof(selector)); return @this.HasValue ? (TResult?)selector(@this.Value) : null; } public static TSource? Where<TSource>( this TSource? @this, Func<TSource, bool> predicate) where TSource : struct { Require.NotNull(predicate, nameof(predicate)); return @this.HasValue && predicate(@this.Value) ? @this : null; } public static TResult? SelectMany<TSource, TMiddle, TResult>( this TSource? @this, Func<TSource, TMiddle?> valueSelector, Func<TSource, TMiddle, TResult> resultSelector) where TSource : struct where TMiddle : struct where TResult : struct { Require.NotNull(valueSelector, nameof(valueSelector)); Require.NotNull(resultSelector, nameof(resultSelector)); if (!@this.HasValue) { return null; } var middle = valueSelector(@this.Value); if (!middle.HasValue) { return null; } return resultSelector(@this.Value, middle.Value); } } } ``` Add one overload for Nullable<T>.SelectMany.
```c# // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo.Applicative { using System; using Narvalo; // Query Expression Pattern for nullables. public static class Qullable { public static TResult? Select<TSource, TResult>(this TSource? @this, Func<TSource, TResult> selector) where TSource : struct where TResult : struct { Require.NotNull(selector, nameof(selector)); return @this is TSource v ? (TResult?)selector(v) : null; } public static TSource? Where<TSource>( this TSource? @this, Func<TSource, bool> predicate) where TSource : struct { Require.NotNull(predicate, nameof(predicate)); return @this is TSource v && predicate(v) ? @this : null; } public static TResult? SelectMany<TSource, TResult>( this TSource? @this, Func<TSource, TResult?> selector) where TSource : struct where TResult : struct { Require.NotNull(selector, nameof(selector)); return @this is TSource v ? selector(v) : null; } public static TResult? SelectMany<TSource, TMiddle, TResult>( this TSource? @this, Func<TSource, TMiddle?> valueSelector, Func<TSource, TMiddle, TResult> resultSelector) where TSource : struct where TMiddle : struct where TResult : struct { Require.NotNull(valueSelector, nameof(valueSelector)); Require.NotNull(resultSelector, nameof(resultSelector)); return @this is TSource v && valueSelector(v) is TMiddle m ? resultSelector(v, m) : (TResult?)null; } } } ```
763b16ec-82e6-4e8f-909f-eed13dc6fcef
{ "language": "C#" }
```c# namespace MvcTurbine.ComponentModel { using System; /// <summary> /// Defines common assemblies to filter. These assemblies are: /// System, mscorlib, Microsoft, WebDev, CppCodeProvider). /// </summary> [Serializable] public class CommonAssemblyFilter : AssemblyFilter { /// <summary> /// Creates an instance and applies the default filters. /// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider). /// </summary> public CommonAssemblyFilter() { AddDefaults(); } /// <summary> /// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider). /// </summary> private void AddDefaults() { AddFilter("System"); AddFilter("mscorlib"); AddFilter("Microsoft"); AddFilter("MvcTurbine"); AddFilter("MvcTurbine.Web"); // Ignore the Visual Studio extra assemblies! AddFilter("WebDev"); AddFilter("CppCodeProvider"); } } }``` Add a comma to the MvcTurbine filters, which will prevent MvcTurbine from being included but not block out MvcTurbine.*.
```c# namespace MvcTurbine.ComponentModel { using System; /// <summary> /// Defines common assemblies to filter. These assemblies are: /// System, mscorlib, Microsoft, WebDev, CppCodeProvider). /// </summary> [Serializable] public class CommonAssemblyFilter : AssemblyFilter { /// <summary> /// Creates an instance and applies the default filters. /// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider). /// </summary> public CommonAssemblyFilter() { AddDefaults(); } /// <summary> /// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider). /// </summary> private void AddDefaults() { AddFilter("System"); AddFilter("mscorlib"); AddFilter("Microsoft"); AddFilter("MvcTurbine,"); AddFilter("MvcTurbine.Web"); // Ignore the Visual Studio extra assemblies! AddFilter("WebDev"); AddFilter("CppCodeProvider"); } } }```
0019965d-c6f5-4c7e-a2ed-6bfc43186005
{ "language": "C#" }
```c# using System.Collections.Generic; using TechSmith.Hyde.Table.Azure; namespace TechSmith.Hyde.Table.Memory { internal class DynamicMemoryQuery : AbstractMemoryQuery<dynamic> { public DynamicMemoryQuery( IEnumerable<GenericTableEntity> entities ) : base( entities ) { } private DynamicMemoryQuery( DynamicMemoryQuery previous ) : base( previous ) { } protected override AbstractQuery<dynamic> CreateCopy() { return new DynamicMemoryQuery( this ); } internal override dynamic Convert( GenericTableEntity e ) { return e.ConvertToDynamic(); } } } ``` Fix issue with null values returned by Memory provider
```c# using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Linq; using TechSmith.Hyde.Table.Azure; namespace TechSmith.Hyde.Table.Memory { internal class DynamicMemoryQuery : AbstractMemoryQuery<dynamic> { public DynamicMemoryQuery( IEnumerable<GenericTableEntity> entities ) : base( entities ) { } private DynamicMemoryQuery( DynamicMemoryQuery previous ) : base( previous ) { } protected override AbstractQuery<dynamic> CreateCopy() { return new DynamicMemoryQuery( this ); } internal override dynamic Convert( GenericTableEntity e ) { return StripNullValues( e.ConvertToDynamic() ); } private static dynamic StripNullValues( dynamic obj ) { dynamic result = new ExpandoObject(); foreach ( var p in ( obj as IDictionary<string, object> ).Where( p => p.Value != null ) ) { ( (IDictionary<string, object>) result ).Add( p ); } return result; } } } ```
5d1bc091-59cc-49c5-9bd4-922a5d2d2321
{ "language": "C#" }
```c# using Hearthstone_Deck_Tracker; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace OptionsDisplay { class HearthWindow : InfoWindow { private HearthstoneTextBlock info; public HearthWindow() { info = new HearthstoneTextBlock(); info.Text = ""; info.FontSize = 12; var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas; var fromTop = canvas.Height / 2; var fromLeft = canvas.Width / 2; Canvas.SetTop(info, fromTop); Canvas.SetLeft(info, fromLeft); canvas.Children.Add(info); } public void AppendWindowText(string text) { info.Text = info.Text + text; } public void ClearAll() { info.Text = ""; } public void MoveToHistory() { return; } public void SetWindowText(string text) { info.Text = text; } } } ``` Add trivial history programming to overlay window to clear each turn
```c# using Hearthstone_Deck_Tracker; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace OptionsDisplay { class HearthWindow : InfoWindow { private HearthstoneTextBlock info; public HearthWindow() { info = new HearthstoneTextBlock(); info.Text = ""; info.FontSize = 12; var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas; var fromTop = canvas.Height / 2; var fromLeft = canvas.Width / 2; Canvas.SetTop(info, fromTop); Canvas.SetLeft(info, fromLeft); canvas.Children.Add(info); } public void AppendWindowText(string text) { info.Text = info.Text + text; } public void ClearAll() { info.Text = ""; } public void MoveToHistory() { info.Text = ""; } public void SetWindowText(string text) { info.Text = text; } } } ```
207972d2-cf78-4017-94cf-943e7e861900
{ "language": "C#" }
```c# namespace NetIRC.Messages { public class PingMessage : IRCMessage, IServerMessage { public string Target { get; } public PingMessage(ParsedIRCMessage parsedMessage) { Target = parsedMessage.Trailing ?? parsedMessage.Parameters[0]; } } } ``` Remove unnecessary null coalescing operator
```c# namespace NetIRC.Messages { public class PingMessage : IRCMessage, IServerMessage { public string Target { get; } public PingMessage(ParsedIRCMessage parsedMessage) { Target = parsedMessage.Trailing; } } } ```
24106f05-9aad-4d6b-871e-724e8657f001
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Platform; namespace osu.Game.Screens.Play { /// <summary> /// Ensures screen is not suspended / dimmed while gameplay is active. /// </summary> public class ScreenSuspensionHandler : Component { private readonly GameplayClockContainer gameplayClockContainer; private Bindable<bool> isPaused; [Resolved] private GameHost host { get; set; } public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer) { this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer)); } protected override void LoadComplete() { base.LoadComplete(); // This is the only usage game-wide of suspension changes. // Assert to ensure we don't accidentally forget this in the future. Debug.Assert(host.AllowScreenSuspension.Value); isPaused = gameplayClockContainer.IsPaused.GetBoundCopy(); isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); isPaused?.UnbindAll(); if (host != null) host.AllowScreenSuspension.Value = true; } } } ``` Apply changes to AllowScreenSuspension bindable
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Platform; namespace osu.Game.Screens.Play { /// <summary> /// Ensures screen is not suspended / dimmed while gameplay is active. /// </summary> public class ScreenSuspensionHandler : Component { private readonly GameplayClockContainer gameplayClockContainer; private Bindable<bool> isPaused; private readonly Bindable<bool> disableSuspensionBindable = new Bindable<bool>(); [Resolved] private GameHost host { get; set; } public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer) { this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer)); } protected override void LoadComplete() { base.LoadComplete(); isPaused = gameplayClockContainer.IsPaused.GetBoundCopy(); isPaused.BindValueChanged(paused => { if (paused.NewValue) host.AllowScreenSuspension.RemoveSource(disableSuspensionBindable); else host.AllowScreenSuspension.AddSource(disableSuspensionBindable); }, true); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); isPaused?.UnbindAll(); host?.AllowScreenSuspension.RemoveSource(disableSuspensionBindable); } } } ```
899d85cf-fc4c-459b-8094-1b0dc9d49d56
{ "language": "C#" }
```c# using System; namespace FalconUDP { internal static class FalconHelper { internal static unsafe void WriteFalconHeader(byte[] dstBuffer, int dstIndex, PacketType type, SendOptions opts, ushort seq, ushort payloadSize) { fixed (byte* ptr = &dstBuffer[dstIndex]) { *ptr = (byte)((byte)opts | (byte)type); *(ushort*)(ptr + 1) = seq; *(ushort*)(ptr + 3) = payloadSize; } } internal static unsafe void WriteAdditionalFalconHeader(byte[] dstBuffer, int dstIndex, PacketType type, SendOptions opts, ushort payloadSize) { fixed (byte* ptr = &dstBuffer[dstIndex]) { *ptr = (byte)((byte)opts | (byte)type); *(ushort*)(ptr + 1) = payloadSize; } } internal static void WriteAck(AckDetail ack, byte[] dstBuffer, int dstIndex) { float ellapsedMilliseconds = ack.EllapsedSecondsSinceEnqueud * 1000; ushort stopoverMilliseconds = ellapsedMilliseconds > ushort.MaxValue ? ushort.MaxValue : (ushort)ellapsedMilliseconds; // TODO log warning if was greater than MaxValue WriteFalconHeader(dstBuffer, dstIndex, ack.Type, ack.Channel, ack.Seq, stopoverMilliseconds); } } } ``` Use float instead of int
```c# using System; namespace FalconUDP { internal static class FalconHelper { internal static unsafe void WriteFalconHeader(byte[] dstBuffer, int dstIndex, PacketType type, SendOptions opts, ushort seq, ushort payloadSize) { fixed (byte* ptr = &dstBuffer[dstIndex]) { *ptr = (byte)((byte)opts | (byte)type); *(ushort*)(ptr + 1) = seq; *(ushort*)(ptr + 3) = payloadSize; } } internal static unsafe void WriteAdditionalFalconHeader(byte[] dstBuffer, int dstIndex, PacketType type, SendOptions opts, ushort payloadSize) { fixed (byte* ptr = &dstBuffer[dstIndex]) { *ptr = (byte)((byte)opts | (byte)type); *(ushort*)(ptr + 1) = payloadSize; } } internal static void WriteAck(AckDetail ack, byte[] dstBuffer, int dstIndex) { float ellapsedMilliseconds = ack.EllapsedSecondsSinceEnqueud * 1000.0f; ushort stopoverMilliseconds = ellapsedMilliseconds > ushort.MaxValue ? ushort.MaxValue : (ushort)ellapsedMilliseconds; // TODO log warning if was greater than MaxValue WriteFalconHeader(dstBuffer, dstIndex, ack.Type, ack.Channel, ack.Seq, stopoverMilliseconds); } } } ```
98d0bda8-648f-48fc-a424-d7a8e1cc1790
{ "language": "C#" }
```c# using System; using System.Security.Principal; using Csla.Serialization; using System.Collections.Generic; using Csla.Core.FieldManager; using System.Runtime.Serialization; using Csla.DataPortalClient; using Csla.Silverlight; using Csla.Core; namespace Csla.Security { public abstract partial class MembershipIdentity : ReadOnlyBase<MembershipIdentity>, IIdentity { public static void GetMembershipIdentity<T>(EventHandler<DataPortalResult<T>> completed, string userName, string password, bool isRunOnWebServer) where T : MembershipIdentity { DataPortal<T> dp = new DataPortal<T>(); dp.FetchCompleted += completed; dp.BeginFetch(new Criteria(userName, password, typeof(T), isRunOnWebServer)); } } } ``` Change MembershipIdentity so it is not an abstract class. bugid: 153
```c# using System; using System.Security.Principal; using Csla.Serialization; using System.Collections.Generic; using Csla.Core.FieldManager; using System.Runtime.Serialization; using Csla.DataPortalClient; using Csla.Silverlight; using Csla.Core; namespace Csla.Security { public partial class MembershipIdentity : ReadOnlyBase<MembershipIdentity>, IIdentity { public static void GetMembershipIdentity<T>(EventHandler<DataPortalResult<T>> completed, string userName, string password, bool isRunOnWebServer) where T : MembershipIdentity { DataPortal<T> dp = new DataPortal<T>(); dp.FetchCompleted += completed; dp.BeginFetch(new Criteria(userName, password, typeof(T), isRunOnWebServer)); } } } ```
b3da98b0-5234-47a2-8d1e-da456c2be1bd
{ "language": "C#" }
```c# namespace Stripe { public static class FilePurpose { public const string AdditionalVerification = "additional_verification"; public const string BusinessIcon = "business_icon"; public const string BusinessLogo = "business_logo"; public const string CustomerSignature = "customer_signature"; public const string DisputeEvidence = "dispute_evidence"; public const string DocumentProviderIdentityDocument = "document_provider_identity_document"; public const string FinanceReportRun = "finance_report_run"; public const string IdentityDocument = "identity_document"; public const string IncorporationArticle = "incorporation_article"; public const string IncorporationDocument = "incorporation_document"; public const string PaymentProviderTransfer = "payment_provider_transfer"; public const string PciDocument = "pci_document"; public const string ProductFeed = "product_feed"; public const string SigmaScheduledQuery = "sigma_scheduled_query"; public const string TaxDocumentUserUpload = "tax_document_user_upload"; } } ``` Add missing enums for File purpose
```c# namespace Stripe { public static class FilePurpose { public const string AccountRequirement = "account_requirement"; public const string AdditionalVerification = "additional_verification"; public const string BusinessIcon = "business_icon"; public const string BusinessLogo = "business_logo"; public const string CustomerSignature = "customer_signature"; public const string DisputeEvidence = "dispute_evidence"; public const string DocumentProviderIdentityDocument = "document_provider_identity_document"; public const string FinanceReportRun = "finance_report_run"; public const string IdentityDocument = "identity_document"; public const string IdentityDocumentDownloadable = "identity_document_downloadable"; public const string IncorporationArticle = "incorporation_article"; public const string IncorporationDocument = "incorporation_document"; public const string PaymentProviderTransfer = "payment_provider_transfer"; public const string PciDocument = "pci_document"; public const string Selfie = "selfie"; public const string ProductFeed = "product_feed"; public const string SigmaScheduledQuery = "sigma_scheduled_query"; public const string TaxDocumentUserUpload = "tax_document_user_upload"; } } ```
00b2452c-d3ad-4830-adb4-bc10d338a038
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; [ExecuteInEditMode] public class ChangeOrderInLayer : MonoBehaviour { #pragma warning disable 0649 [SerializeField] private Renderer _renderer; [SerializeField] private int orderInLayer; #pragma warning restore 0649 void Start() { if (_renderer == null) _renderer = GetComponent<Renderer>(); _renderer.sortingOrder = orderInLayer; } void Update () { if (orderInLayer != _renderer.sortingOrder) _renderer.sortingOrder = orderInLayer; } } ``` Add disableOnPlay option to changeOrderInLayer
```c# using UnityEngine; using System.Collections; [ExecuteInEditMode] public class ChangeOrderInLayer : MonoBehaviour { [SerializeField] private Renderer _renderer; [SerializeField] private int orderInLayer; [SerializeField] private string sortingLayer = "Default"; [SerializeField] private bool disableOnPlay = true; private void Awake() { if (disableOnPlay && Application.isPlaying) enabled = false; } void Start() { if (_renderer == null) _renderer = GetComponent<Renderer>(); _renderer.sortingOrder = orderInLayer; } void Update () { if (orderInLayer != _renderer.sortingOrder) _renderer.sortingOrder = orderInLayer; if (!string.IsNullOrEmpty(sortingLayer)) _renderer.sortingLayerName = sortingLayer; } } ```
134dcc86-b4b1-439b-9a84-826c113a3af5
{ "language": "C#" }
```c# using FluentAssertions; using FluentAssertions.Execution; namespace Bearded.Utilities.Testing { public sealed class MaybeAssertions<T> { private readonly Maybe<T> subject; public MaybeAssertions(Maybe<T> instance) => subject = instance; [CustomAssertion] public void BeJust(T value, string because = "", params object[] becauseArgs) { BeJust().Which.Should().BeEquivalentTo(value, because, becauseArgs); } [CustomAssertion] public AndWhichConstraint<MaybeAssertions<T>, T> BeJust(string because = "", params object[] becauseArgs) { var onValueCalled = false; var matched = default(T); subject.Match( onValue: actual => { onValueCalled = true; matched = actual; }, onNothing: () => { }); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(onValueCalled) .FailWith("Expected maybe to have value, but had none."); return new AndWhichConstraint<MaybeAssertions<T>, T>(this, matched); } [CustomAssertion] public void BeNothing(string because = "", params object[] becauseArgs) { var onNothingCalled = false; subject.Match(onValue: _ => { }, onNothing: () => onNothingCalled = true); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(onNothingCalled) .FailWith("Expected maybe to be nothing, but had value."); } } } ``` Use Be instead of BeEquivalentTo
```c# using FluentAssertions; using FluentAssertions.Execution; namespace Bearded.Utilities.Testing { public sealed class MaybeAssertions<T> { private readonly Maybe<T> subject; public MaybeAssertions(Maybe<T> instance) => subject = instance; [CustomAssertion] public void BeJust(T value, string because = "", params object[] becauseArgs) { BeJust().Which.Should().Be(value, because, becauseArgs); } [CustomAssertion] public AndWhichConstraint<MaybeAssertions<T>, T> BeJust(string because = "", params object[] becauseArgs) { var onValueCalled = false; var matched = default(T); subject.Match( onValue: actual => { onValueCalled = true; matched = actual; }, onNothing: () => { }); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(onValueCalled) .FailWith("Expected maybe to have value, but had none."); return new AndWhichConstraint<MaybeAssertions<T>, T>(this, matched); } [CustomAssertion] public void BeNothing(string because = "", params object[] becauseArgs) { var onNothingCalled = false; subject.Match(onValue: _ => { }, onNothing: () => onNothingCalled = true); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(onNothingCalled) .FailWith("Expected maybe to be nothing, but had value."); } } } ```
5064f45a-381f-4f1c-8d2b-31ccaa31fc5d
{ "language": "C#" }
```c# using System.Security.Cryptography.X509Certificates; using NUnit.Framework; using Procon.Service.Shared; using Procon.Setup.Models; namespace Procon.Setup.Test.Models { [TestFixture] public class CertificateModelTest { /// <summary> /// Tests a certificate will be generated and can be read by .NET /// </summary> [Test] public void TestGenerate() { CertificateModel model = new CertificateModel(); // Delete the certificate if it exists. Defines.CertificatesDirectoryCommandServerPfx.Delete(); // Create a new certificate model.Generate(); // Certificate exists Assert.IsTrue(Defines.CertificatesDirectoryCommandServerPfx.Exists); // Loads the certificates var loadedCertificate = new X509Certificate2(Defines.CertificatesDirectoryCommandServerPfx.FullName, model.Password); // Certificate can be loaded. Assert.IsNotNull(loadedCertificate); Assert.IsNotNull(loadedCertificate.PrivateKey); } } } ``` Fix certificate generation not refreshing test
```c# using System.Security.Cryptography.X509Certificates; using NUnit.Framework; using Procon.Service.Shared; using Procon.Setup.Models; namespace Procon.Setup.Test.Models { [TestFixture] public class CertificateModelTest { /// <summary> /// Tests a certificate will be generated and can be read by .NET /// </summary> [Test] public void TestGenerate() { CertificateModel model = new CertificateModel(); // Delete the certificate if it exists. Defines.CertificatesDirectoryCommandServerPfx.Delete(); // Create a new certificate model.Generate(); // Certificate exists Defines.CertificatesDirectoryCommandServerPfx.Refresh(); Assert.IsTrue(Defines.CertificatesDirectoryCommandServerPfx.Exists); // Loads the certificates var loadedCertificate = new X509Certificate2(Defines.CertificatesDirectoryCommandServerPfx.FullName, model.Password); // Certificate can be loaded. Assert.IsNotNull(loadedCertificate); Assert.IsNotNull(loadedCertificate.PrivateKey); } } } ```
0a5209a0-00f7-46ca-b0ac-51729ca48db8
{ "language": "C#" }
```c# namespace BigEgg.Tools.JsonComparer.Parameters { using BigEgg.Tools.ConsoleExtension.Parameters; [Command("split", "Split the big JSON file to multiple small files.")] public class SplitParameter { [StringProperty("input", "i", "The path of JSON file to split.", Required = true)] public string FileName { get; set; } [StringProperty("output", "o", "The path to store the splited JSON files.", Required = true)] public string OutputPath { get; set; } [StringProperty("node_name", "n", "The name of node to split.", Required = true)] public string NodeName { get; set; } [StringProperty("output_pattern", "op", "The output file name pattern. Use '${name}' for node name, ${index} for the child index.")] public string OutputFileNamePattern { get; set; } } } ``` Fix the help message of output_pattern
```c# namespace BigEgg.Tools.JsonComparer.Parameters { using BigEgg.Tools.ConsoleExtension.Parameters; [Command("split", "Split the big JSON file to multiple small files.")] public class SplitParameter { [StringProperty("input", "i", "The path of JSON file to split.", Required = true)] public string FileName { get; set; } [StringProperty("output", "o", "The path to store the splited JSON files.", Required = true)] public string OutputPath { get; set; } [StringProperty("node_name", "n", "The name of node to split.", Required = true)] public string NodeName { get; set; } [StringProperty("output_pattern", "op", "The output file name pattern. Use '${name}' for node name, '${index}' for the child index.")] public string OutputFileNamePattern { get; set; } } } ```
dc8f0a0e-5888-4b94-ba12-87c01e7572c4
{ "language": "C#" }
```c# using System.IO; using System.Linq; using SpotifyRecorder.Core.Abstractions.Entities; using SpotifyRecorder.Core.Abstractions.Services; using TagLib; using TagLib.Id3v2; using File = TagLib.File; namespace SpotifyRecorder.Core.Implementations.Services { public class ID3TagService : IID3TagService { public ID3Tags GetTags(RecordedSong song) { var tagFile = File.Create(new MemoryFileAbstraction(new MemoryStream(song.Data))); return new ID3Tags { Title = tagFile.Tag.Title, Artists = tagFile.Tag.Performers, Picture = tagFile.Tag.Pictures.FirstOrDefault()?.Data.Data }; } public void UpdateTags(ID3Tags tags, RecordedSong song) { using (var stream = new MemoryStream(song.Data.Length + 1000)) { stream.Write(song.Data, 0, song.Data.Length); stream.Position = 0; var tagFile = File.Create(new MemoryFileAbstraction(stream)); tagFile.Tag.Title = tags.Title; tagFile.Tag.Performers = tags.Artists; if (tags.Picture != null) { tagFile.Tag.Pictures = new IPicture[] { new Picture(new ByteVector(tags.Picture, tags.Picture.Length)), }; } tagFile.Save(); song.Data = stream.ToArray(); } } } }``` Improve how much space we reserve for tag changes
```c# using System.IO; using System.Linq; using SpotifyRecorder.Core.Abstractions.Entities; using SpotifyRecorder.Core.Abstractions.Services; using TagLib; using TagLib.Id3v2; using File = TagLib.File; namespace SpotifyRecorder.Core.Implementations.Services { public class ID3TagService : IID3TagService { public ID3Tags GetTags(RecordedSong song) { var tagFile = File.Create(new MemoryFileAbstraction(new MemoryStream(song.Data))); return new ID3Tags { Title = tagFile.Tag.Title, Artists = tagFile.Tag.Performers, Picture = tagFile.Tag.Pictures.FirstOrDefault()?.Data.Data }; } public void UpdateTags(ID3Tags tags, RecordedSong song) { using (var stream = new MemoryStream(song.Data.Length * 2)) { stream.Write(song.Data, 0, song.Data.Length); stream.Position = 0; var tagFile = File.Create(new MemoryFileAbstraction(stream)); tagFile.Tag.Title = tags.Title; tagFile.Tag.Performers = tags.Artists; if (tags.Picture != null) { tagFile.Tag.Pictures = new IPicture[] { new Picture(new ByteVector(tags.Picture, tags.Picture.Length)), }; } tagFile.Save(); song.Data = stream.ToArray(); } } } }```
f0494cc9-e2f5-4d8e-9be8-348ff362c27b
{ "language": "C#" }
```c# using System.Collections.Generic; using Autofac.Core; namespace Autofac { /// <summary> /// The details of an individual request to resolve a service. /// </summary> public class ResolveRequest { /// <summary> /// Initializes a new instance of the <see cref="ResolveRequest"/> class. /// </summary> /// <param name="service">The service being resolved.</param> /// <param name="registration">The component registration for the service.</param> /// <param name="parameters">The parameters used when resolving the service.</param> /// <param name="decoratorTarget">The target component to be decorated.</param> public ResolveRequest(Service service, IComponentRegistration registration, IEnumerable<Parameter> parameters, IComponentRegistration? decoratorTarget = null) { Service = service; Registration = registration; Parameters = parameters; DecoratorTarget = decoratorTarget; } /// <summary> /// Gets the service being resolved. /// </summary> public Service Service { get; } /// <summary> /// Gets the component registration for the service being resolved. /// </summary> public IComponentRegistration Registration { get; } /// <summary> /// Gets the parameters used when resolving the service. /// </summary> public IEnumerable<Parameter> Parameters { get; } /// <summary> /// Gets the component registration for the decorator target if configured. /// </summary>2 public IComponentRegistration? DecoratorTarget { get; } } } ``` Remove extra char that sneaked onto XML comment
```c# using System.Collections.Generic; using Autofac.Core; namespace Autofac { /// <summary> /// The details of an individual request to resolve a service. /// </summary> public class ResolveRequest { /// <summary> /// Initializes a new instance of the <see cref="ResolveRequest"/> class. /// </summary> /// <param name="service">The service being resolved.</param> /// <param name="registration">The component registration for the service.</param> /// <param name="parameters">The parameters used when resolving the service.</param> /// <param name="decoratorTarget">The target component to be decorated.</param> public ResolveRequest(Service service, IComponentRegistration registration, IEnumerable<Parameter> parameters, IComponentRegistration? decoratorTarget = null) { Service = service; Registration = registration; Parameters = parameters; DecoratorTarget = decoratorTarget; } /// <summary> /// Gets the service being resolved. /// </summary> public Service Service { get; } /// <summary> /// Gets the component registration for the service being resolved. /// </summary> public IComponentRegistration Registration { get; } /// <summary> /// Gets the parameters used when resolving the service. /// </summary> public IEnumerable<Parameter> Parameters { get; } /// <summary> /// Gets the component registration for the decorator target if configured. /// </summary> public IComponentRegistration? DecoratorTarget { get; } } } ```
ca6322fc-5c55-40ba-848e-632475b65178
{ "language": "C#" }
```c# // Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using CefSharp.Internals; namespace CefSharp { internal static class InternalWebBrowserExtensions { internal static void SetHandlersToNull(this IWebBrowserInternal browser) { browser.ResourceHandlerFactory = null; browser.JsDialogHandler = null; browser.DialogHandler = null; browser.DownloadHandler = null; browser.KeyboardHandler = null; browser.LifeSpanHandler = null; browser.MenuHandler = null; browser.FocusHandler = null; browser.RequestHandler = null; browser.DragHandler = null; browser.GeolocationHandler = null; } } } ``` Set RenderProcessMessageHandler and LoadHandler to null on Dispose Reoder so they match the order in IWebBrowser so they're easier to compare
```c# // Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using CefSharp.Internals; namespace CefSharp { internal static class InternalWebBrowserExtensions { internal static void SetHandlersToNull(this IWebBrowserInternal browser) { browser.DialogHandler = null; browser.RequestHandler = null; browser.DisplayHandler = null; browser.LoadHandler = null; browser.LifeSpanHandler = null; browser.KeyboardHandler = null; browser.JsDialogHandler = null; browser.DragHandler = null; browser.DownloadHandler = null; browser.MenuHandler = null; browser.FocusHandler = null; browser.ResourceHandlerFactory = null; browser.GeolocationHandler = null; browser.RenderProcessMessageHandler = null; } } } ```
f4ab349d-2d3d-4664-9d66-2b5d8f293dc1
{ "language": "C#" }
```c# /* Copyright 2015 Google Inc 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.Reflection; // Attributes common to all assemblies. [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyCopyright("Copyright 2016 Google Inc")] [assembly: AssemblyVersion("1.11.0.*")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] ``` Fix revision number of support libraries to 0
```c# /* Copyright 2015 Google Inc 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.Reflection; // Attributes common to all assemblies. [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyCopyright("Copyright 2016 Google Inc")] [assembly: AssemblyVersion("1.11.0.0")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] ```
8045ddd6-25f2-4a1d-9f6f-844fedb7d2d7
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using System.IO; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Standard; namespace NuGetGallery { public class PerFieldAnalyzer : PerFieldAnalyzerWrapper { public PerFieldAnalyzer() : base(new StandardAnalyzer(LuceneCommon.LuceneVersion), CreateFieldAnalyzers()) { } private static IDictionary CreateFieldAnalyzers() { return new Dictionary<string, Analyzer>(StringComparer.OrdinalIgnoreCase) { { "Title", new TitleAnalyzer() } }; } class TitleAnalyzer : Analyzer { private readonly Analyzer innerAnalyzer = new StandardAnalyzer(LuceneCommon.LuceneVersion); public override TokenStream TokenStream(string fieldName, TextReader reader) { // Split the title based on IdSeparators, then run it through the standardAnalyzer string title = reader.ReadToEnd(); string partiallyTokenized = String.Join(" ", title.Split(LuceneIndexingService.IdSeparators, StringSplitOptions.RemoveEmptyEntries)); return innerAnalyzer.TokenStream(fieldName, new StringReader(partiallyTokenized)); } } } }``` Stop filtering out stop words in package ids and titles.
```c# using System; using System.Collections; using System.Collections.Generic; using System.IO; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Standard; namespace NuGetGallery { public class PerFieldAnalyzer : PerFieldAnalyzerWrapper { public PerFieldAnalyzer() : base(new StandardAnalyzer(LuceneCommon.LuceneVersion), CreateFieldAnalyzers()) { } private static IDictionary CreateFieldAnalyzers() { // For idAnalyzer we use the 'standard analyzer' but with no stop words (In, Of, The, etc are indexed). var stopWords = new Hashtable(); StandardAnalyzer idAnalyzer = new StandardAnalyzer(LuceneCommon.LuceneVersion, stopWords); return new Dictionary<string, Analyzer>(StringComparer.OrdinalIgnoreCase) { { "Id", idAnalyzer }, { "Title", new TitleAnalyzer() }, }; } class TitleAnalyzer : Analyzer { private readonly StandardAnalyzer innerAnalyzer; public TitleAnalyzer() { // For innerAnalyzer we use the 'standard analyzer' but with no stop words (In, Of, The, etc are indexed). var stopWords = new Hashtable(); innerAnalyzer = new StandardAnalyzer(LuceneCommon.LuceneVersion, stopWords); } public override TokenStream TokenStream(string fieldName, TextReader reader) { // Split the title based on IdSeparators, then run it through the innerAnalyzer string title = reader.ReadToEnd(); string partiallyTokenized = String.Join(" ", title.Split(LuceneIndexingService.IdSeparators, StringSplitOptions.RemoveEmptyEntries)); return innerAnalyzer.TokenStream(fieldName, new StringReader(partiallyTokenized)); } } } }```