doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
2e9cc72a-2699-4dcf-926b-6e5d191e080c | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
}
}
```
Use the term response instead of request. | ```c#
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] {
"This is a CORS response.",
"It works from any origin."
};
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] {
"This is a CORS response.",
"It works only from www.bigfont.ca AND from the same origin."
};
}
}
}
``` |
a68afac7-6e21-4b40-8414-6f92dfc24079 | {
"language": "C#"
} | ```c#
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace WebPackAngular2TypeScript.Routing
{
public class DeepLinkingMiddleware
{
public DeepLinkingMiddleware(RequestDelegate next,
IHostingEnvironment hostingEnv,
ILoggerFactory loggerFactory,
DeepLinkingOptions options)
{
this.next = next;
this.options = options;
staticFileMiddleware = new StaticFileMiddleware(next,
hostingEnv, options.FileServerOptions.StaticFileOptions, loggerFactory);
}
public async Task Invoke(HttpContext context)
{
// try to resolve the request with default static file middleware
await staticFileMiddleware.Invoke(context);
if (context.Response.StatusCode == 404)
{
var redirectUrlPath = FindRedirection(context);
if (redirectUrlPath != unresolvedPath)
{
context.Request.Path = redirectUrlPath;
await staticFileMiddleware.Invoke(context);
}
}
}
protected virtual PathString FindRedirection(HttpContext context)
{
// route to root path when request was not resolved
return options.RedirectUrlPath;
}
protected readonly DeepLinkingOptions options;
protected readonly RequestDelegate next;
protected readonly StaticFileMiddleware staticFileMiddleware;
protected readonly PathString unresolvedPath = null;
}
}
```
Fix spurious 404 response when deep linking to a client route | ```c#
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace WebPackAngular2TypeScript.Routing
{
public class DeepLinkingMiddleware
{
public DeepLinkingMiddleware(RequestDelegate next,
IHostingEnvironment hostingEnv,
ILoggerFactory loggerFactory,
DeepLinkingOptions options)
{
this.next = next;
this.options = options;
staticFileMiddleware = new StaticFileMiddleware(next,
hostingEnv, options.FileServerOptions.StaticFileOptions, loggerFactory);
}
public async Task Invoke(HttpContext context)
{
// try to resolve the request with default static file middleware
await staticFileMiddleware.Invoke(context);
if (context.Response.StatusCode == StatusCodes.Status404NotFound)
{
var redirectUrlPath = FindRedirection(context);
if (redirectUrlPath != unresolvedPath)
{
// if resolved, reset response as successful
context.Response.StatusCode = StatusCodes.Status200OK;
context.Request.Path = redirectUrlPath;
await staticFileMiddleware.Invoke(context);
}
}
}
protected virtual PathString FindRedirection(HttpContext context)
{
// route to root path when request was not resolved
return options.RedirectUrlPath;
}
protected readonly DeepLinkingOptions options;
protected readonly RequestDelegate next;
protected readonly StaticFileMiddleware staticFileMiddleware;
protected readonly PathString unresolvedPath = null;
}
}
``` |
404b3d4e-2ef3-4531-9c8f-d9c21c9864b4 | {
"language": "C#"
} | ```c#
@using Dashboard
@using Microsoft.WindowsAzure.Jobs
@{
ViewBag.Title = "Configuration Error";
}
<h2>Bad Config</h2>
<p>
The configuration is not properly set for the Windows Azure Web Jobs SDK Dashboard.
In your configuration (such as web.config), you must set a connection string named <i>@JobHost.LoggingConnectionStringName</i> that points to the account connection string where the sb logs are being stored. EG, under "connectionStrings" in Web.config, add a value like:
</p>
<pre>
<add name="@JobHost.LoggingConnectionStringName" value="DefaultEndpointsProtocol=https;AccountName=<b>NAME</b>;AccountKey=<b>KEY</b>" />
</pre>
<p>
This is the storage account that your user functions will bind against. This is also where logging will be stored.
</p>
<p class="alert alert-danger">@SimpleBatchStuff.BadInitErrorMessage</p>```
Fix connectionStrings section attribute in BadConfig doc page | ```c#
@using Dashboard
@using Microsoft.WindowsAzure.Jobs
@{
ViewBag.Title = "Configuration Error";
}
<h2>Bad Config</h2>
<p>
The configuration is not properly set for the Windows Azure Web Jobs SDK Dashboard.
In your configuration (such as web.config), you must set a connection string named <i>@JobHost.LoggingConnectionStringName</i> that points to the account connection string where the sb logs are being stored. EG, under "connectionStrings" in Web.config, add a value like:
</p>
<pre>
<add name="@JobHost.LoggingConnectionStringName" connectionString="DefaultEndpointsProtocol=https;AccountName=<b>NAME</b>;AccountKey=<b>KEY</b>" />
</pre>
<p>
This is the storage account that your user functions will bind against. This is also where logging will be stored.
</p>
<p class="alert alert-danger">@SimpleBatchStuff.BadInitErrorMessage</p>``` |
36a41c07-6850-4780-80e1-a8c5933a5cf4 | {
"language": "C#"
} | ```c#
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace RepoZ.UI.Mac.Story
{
public class StringCommandHandler
{
private Dictionary<string, Action> _commands = new Dictionary<string, Action>();
private StringBuilder _helpBuilder = new StringBuilder();
internal bool IsCommand(string value)
{
return value?.StartsWith(":") == true;
}
internal bool Handle(string command)
{
if (_commands.TryGetValue(CleanCommand(command), out Action commandAction))
{
commandAction.Invoke();
return true;
}
return false;
}
internal void Define(string[] commands, Action commandAction, string helpText)
{
foreach (var command in commands)
_commands[CleanCommand(command)] = commandAction;
if (_helpBuilder.Length > 0)
_helpBuilder.AppendLine("");
_helpBuilder.AppendLine(string.Join(", ", commands.OrderBy(c => c)));
_helpBuilder.AppendLine("\t"+ helpText);
}
private string CleanCommand(string command)
{
command = command?.Trim().ToLower() ?? "";
return command.StartsWith(":", StringComparison.OrdinalIgnoreCase) ? command.Substring(1) : command;
}
internal string GetHelpText() => _helpBuilder.ToString();
}
}```
Enhance the Mac command reference text a bit | ```c#
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace RepoZ.UI.Mac.Story
{
public class StringCommandHandler
{
private Dictionary<string, Action> _commands = new Dictionary<string, Action>();
private StringBuilder _helpBuilder = new StringBuilder();
internal bool IsCommand(string value)
{
return value?.StartsWith(":") == true;
}
internal bool Handle(string command)
{
if (_commands.TryGetValue(CleanCommand(command), out Action commandAction))
{
commandAction.Invoke();
return true;
}
return false;
}
internal void Define(string[] commands, Action commandAction, string helpText)
{
foreach (var command in commands)
_commands[CleanCommand(command)] = commandAction;
if (_helpBuilder.Length == 0)
{
_helpBuilder.AppendLine("To execute a command instead of filtering the list of repositories, simply begin with a colon (:).");
_helpBuilder.AppendLine("");
_helpBuilder.AppendLine("Command reference:");
}
_helpBuilder.AppendLine("");
_helpBuilder.AppendLine("\t:" + string.Join(" or :", commands.OrderBy(c => c)));
_helpBuilder.AppendLine("\t\t"+ helpText);
}
private string CleanCommand(string command)
{
command = command?.Trim().ToLower() ?? "";
return command.StartsWith(":", StringComparison.OrdinalIgnoreCase) ? command.Substring(1) : command;
}
internal string GetHelpText() => _helpBuilder.ToString();
}
}``` |
e25eb65f-7909-4b1c-b469-392aebf826d3 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ActionMailer.Net.Mvc;
using RationalVote.Models;
using System.Configuration;
namespace RationalVote.Controllers
{
public class MailController : MailerBase
{
public static string GetFromEmail( string purpose )
{
return String.Format( "\"{0} {1}\" <{2}>",
ConfigurationManager.AppSettings.Get("siteTitle"),
purpose,
ConfigurationManager.AppSettings.Get("emailFrom") );
}
public EmailResult VerificationEmail( User model, EmailVerificationToken token )
{
To.Add( model.Email );
From = GetFromEmail( "Verification" );
Subject = "Please verify your account";
ViewBag.Token = token.Token;
return Email( "VerificationEmail" );
}
public EmailResult ExceptionEmail( HttpException e, string message )
{
To.Add( ConfigurationManager.AppSettings.Get( "ServerAdmin" ) );
From = GetFromEmail( "Exception" );
Subject = "Site exception - " + message;
ViewBag.Exception = e.ToString();
return Email( "ExceptionEmail" );
}
}
}```
Use site title in email subject for exception handler. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ActionMailer.Net.Mvc;
using RationalVote.Models;
using System.Configuration;
namespace RationalVote.Controllers
{
public class MailController : MailerBase
{
public static string GetFromEmail( string purpose )
{
return String.Format( "\"{0} {1}\" <{2}>",
ConfigurationManager.AppSettings.Get("siteTitle"),
purpose,
ConfigurationManager.AppSettings.Get("emailFrom") );
}
public EmailResult VerificationEmail( User model, EmailVerificationToken token )
{
To.Add( model.Email );
From = GetFromEmail( "Verification" );
Subject = "Please verify your account";
ViewBag.Token = token.Token;
return Email( "VerificationEmail" );
}
public EmailResult ExceptionEmail( HttpException e, string message )
{
To.Add( ConfigurationManager.AppSettings.Get( "ServerAdmin" ) );
From = GetFromEmail( "Exception" );
Subject = ConfigurationManager.AppSettings.Get("siteTitle") + " exception - " + message;
ViewBag.Exception = e.ToString();
return Email( "ExceptionEmail" );
}
}
}``` |
76e1f703-077f-45a9-bcd2-3149c1a029b4 | {
"language": "C#"
} | ```c#
namespace InfoCarrier.Core.EFCore.FunctionalTests
{
using Microsoft.EntityFrameworkCore.Specification.Tests;
using Xunit;
public class BuiltInDataTypesInfoCarrierTest : BuiltInDataTypesTestBase<BuiltInDataTypesInfoCarrierFixture>
{
public BuiltInDataTypesInfoCarrierTest(BuiltInDataTypesInfoCarrierFixture fixture)
: base(fixture)
{
}
[Fact]
public virtual void Can_perform_query_with_ansi_strings()
{
this.Can_perform_query_with_ansi_strings(supportsAnsi: false);
}
}
}
```
Use SequenceEqual instead of operator== for comparison of arrays in 'Can_perform_query_with_max_length' test | ```c#
namespace InfoCarrier.Core.EFCore.FunctionalTests
{
using System.Linq;
using Microsoft.EntityFrameworkCore.Specification.Tests;
using Xunit;
public class BuiltInDataTypesInfoCarrierTest : BuiltInDataTypesTestBase<BuiltInDataTypesInfoCarrierFixture>
{
public BuiltInDataTypesInfoCarrierTest(BuiltInDataTypesInfoCarrierFixture fixture)
: base(fixture)
{
}
[Fact]
public virtual void Can_perform_query_with_ansi_strings()
{
this.Can_perform_query_with_ansi_strings(supportsAnsi: false);
}
[Fact]
public override void Can_perform_query_with_max_length()
{
// UGLY: this is a complete copy-n-paste of
// https://github.com/aspnet/EntityFramework/blob/rel/1.1.0/src/Microsoft.EntityFrameworkCore.Specification.Tests/BuiltInDataTypesTestBase.cs#L25
// We only use SequenceEqual instead of operator== for comparison of arrays.
var shortString = "Sky";
var shortBinary = new byte[] { 8, 8, 7, 8, 7 };
var longString = new string('X', 9000);
var longBinary = new byte[9000];
for (var i = 0; i < longBinary.Length; i++)
{
longBinary[i] = (byte)i;
}
using (var context = this.CreateContext())
{
context.Set<MaxLengthDataTypes>().Add(
new MaxLengthDataTypes
{
Id = 799,
String3 = shortString,
ByteArray5 = shortBinary,
String9000 = longString,
ByteArray9000 = longBinary
});
Assert.Equal(1, context.SaveChanges());
}
using (var context = this.CreateContext())
{
Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.String3 == shortString));
Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.ByteArray5.SequenceEqual(shortBinary)));
Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.String9000 == longString));
Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.ByteArray9000.SequenceEqual(longBinary)));
}
}
}
}
``` |
6cdddb91-5177-4ac2-a19b-f47e957300af | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace WebAPIApplication.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
[Route("ping")]
public string Ping()
{
return "All good. You don't need to be authenticated to call this.";
}
[Authorize]
[HttpGet]
[Route("secured/ping")]
public string PingSecured()
{
return "All good. You only get this message if you are authenticated.";
}
}
}
```
Return JSON object from Values controller | ```c#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace WebAPIApplication.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
[Route("ping")]
public dynamic Ping()
{
return new {
message = "All good. You don't need to be authenticated to call this."
};
}
[Authorize]
[HttpGet]
[Route("secured/ping")]
public object PingSecured()
{
return new {
message = "All good. You only get this message if you are authenticated."
};
}
}
}
``` |
5486b210-6240-4b8e-8f48-262d576f538f | {
"language": "C#"
} | ```c#
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using Scriban.Runtime;
namespace Scriban.Syntax
{
[ScriptSyntax("capture statement", "capture <variable> ... end")]
public class ScriptCaptureStatement : ScriptStatement
{
public ScriptExpression Target { get; set; }
public ScriptBlockStatement Body { get; set; }
public override object Evaluate(TemplateContext context)
{
// unit test: 230-capture-statement.txt
context.PushOutput();
{
context.Evaluate(Body);
}
var result = context.PopOutput();
context.SetValue(Target, result);
return null;
}
}
}```
Make sure a capture will not leave the TemplateContext in an unbalanced state if an exception occurs | ```c#
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using Scriban.Runtime;
namespace Scriban.Syntax
{
[ScriptSyntax("capture statement", "capture <variable> ... end")]
public class ScriptCaptureStatement : ScriptStatement
{
public ScriptExpression Target { get; set; }
public ScriptBlockStatement Body { get; set; }
public override object Evaluate(TemplateContext context)
{
// unit test: 230-capture-statement.txt
context.PushOutput();
try
{
context.Evaluate(Body);
}
finally
{
var result = context.PopOutput();
context.SetValue(Target, result);
}
return null;
}
}
}``` |
8cb16e21-f898-41b7-8fca-5d6742f8e0f2 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Configuration")]
[assembly: AssemblyDescription("")]
```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Configuration")]
``` |
aeb6bd79-63ac-4998-abaa-6dcb032a1b37 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.Mvc")]
[assembly: AssemblyDescription("")]
```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.Mvc")]
``` |
261f8358-1c18-4854-98b1-f6511c6edf5f | {
"language": "C#"
} | ```c#
using System.Configuration;
using Microsoft.Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using SFA.DAS.EmployerFinance.Api;
[assembly: OwinStartup(typeof(Startup))]
namespace SFA.DAS.EmployerFinance.Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
_ = app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["idaTenant"],
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
ValidAudiences = ConfigurationManager.AppSettings["FinanceApiIdentifierUri"].ToString().Split(',')
}
});
}
}
}
```
Rename app setting for finance api audiences | ```c#
using System.Configuration;
using Microsoft.Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using SFA.DAS.EmployerFinance.Api;
[assembly: OwinStartup(typeof(Startup))]
namespace SFA.DAS.EmployerFinance.Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
_ = app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["idaTenant"],
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
ValidAudiences = ConfigurationManager.AppSettings["FinanceApiIdaAudience"].ToString().Split(',')
}
});
}
}
}
``` |
5a54b242-41c1-4ed0-b531-64c4ca6fa52a | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace CroquetAustraliaWebsite.Application.App.Infrastructure
{
public static class PublicNavigationBar
{
public static IEnumerable<NavigationItem> GetNavigationItems()
{
return new[]
{
new NavigationItem("Contact Us",
new NavigationItem("Office & Board", "~/governance/contact-us"),
new NavigationItem("Committees", "~/governance/contact-us#committees"),
new NavigationItem("Appointed Officers", "~/governance/contact-us#appointed-officers"),
new NavigationItem("State Associations", "~/governance/state-associations")),
new NavigationItem("Governance",
new NavigationItem("Background", "~/governance/background"),
new NavigationItem("Constitution, Regulations & Policies", "~/governance/constitution-regulations-and-policies"),
new NavigationItem("Members", "~/governance/members")),
new NavigationItem("Tournaments", "~/tournaments"),
new NavigationItem("Disciplines",
new NavigationItem("Association Croquet",
new NavigationItem("Coaching", "~/disciplines/association-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/association-croquet/refereeing")),
new NavigationItem("Golf Croquet",
new NavigationItem("Coaching", "~/disciplines/golf-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/golf-croquet/refereeing"),
new NavigationItem("Resources", "~/disciplines/golf-croquet/resources")))
};
}
}
}
```
Add 'Board Meeting Minutes' to navigation bar | ```c#
using System.Collections.Generic;
namespace CroquetAustraliaWebsite.Application.App.Infrastructure
{
public static class PublicNavigationBar
{
public static IEnumerable<NavigationItem> GetNavigationItems()
{
return new[]
{
new NavigationItem("Contact Us",
new NavigationItem("Office & Board", "~/governance/contact-us"),
new NavigationItem("Committees", "~/governance/contact-us#committees"),
new NavigationItem("Appointed Officers", "~/governance/contact-us#appointed-officers"),
new NavigationItem("State Associations", "~/governance/state-associations")),
new NavigationItem("Governance",
new NavigationItem("Background", "~/governance/background"),
new NavigationItem("Constitution, Regulations & Policies", "~/governance/constitution-regulations-and-policies"),
new NavigationItem("Members", "~/governance/members"),
new NavigationItem("Board Meeting Minutes", "~/governance/minutes/board-meeting-minutes")),
new NavigationItem("Tournaments", "~/tournaments"),
new NavigationItem("Disciplines",
new NavigationItem("Association Croquet",
new NavigationItem("Coaching", "~/disciplines/association-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/association-croquet/refereeing")),
new NavigationItem("Golf Croquet",
new NavigationItem("Coaching", "~/disciplines/golf-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/golf-croquet/refereeing"),
new NavigationItem("Resources", "~/disciplines/golf-croquet/resources")))
};
}
}
}
``` |
02a80a3a-e3aa-43c3-8c83-c1f14f0bb0e3 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
namespace Abc.NCrafts.Quizz.Performance.Questions._028
{
[CorrectAnswer(Difficulty = Difficulty.Medium)]
public class Answer1
{
public static void Run()
{
// begin
var primes = Enumerable.Range(0, 10 * 1000)
.Where(IsPrime)
.ToList();
// end
Logger.Log("Primes: {0}", primes.Count);
}
private static bool IsPrime(int number)
{
if (number == 0 || number == 1) return false;
if (number == 2) return true;
for (var divisor = 2; divisor < (int)Math.Sqrt(number); divisor++)
{
if (number % divisor == 0) return false;
}
return true;
}
}
}```
Fix answer 28 to include square roots in prime test | ```c#
using System;
using System.Linq;
namespace Abc.NCrafts.Quizz.Performance.Questions._028
{
[CorrectAnswer(Difficulty = Difficulty.Medium)]
public class Answer1
{
public static void Run()
{
// begin
var primes = Enumerable.Range(0, 10 * 1000)
.Where(IsPrime)
.ToList();
// end
Logger.Log("Primes: {0}", primes.Count);
}
private static bool IsPrime(int number)
{
if (number == 0 || number == 1) return false;
if (number == 2) return true;
for (var divisor = 2; divisor <= (int)Math.Sqrt(number); divisor++)
{
if (number % divisor == 0) return false;
}
return true;
}
}
}``` |
960fedf2-cfd3-4d70-aad6-e089c9fa0ba1 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using Microsoft.Extensions.Configuration;
using Xunit;
using SocksSharp;
using SocksSharp.Proxy;
namespace SocksSharp.Tests
{
public class ProxyClientTests
{
private ProxySettings proxySettings;
private void GatherTestConfiguration()
{
var appConfigMsgWarning = "{0} not configured in proxysettings.json! Some tests may fail.";
var builder = new ConfigurationBuilder()
.AddJsonFile("proxysettings.json")
.Build();
proxySettings = new ProxySettings();
var host = builder["host"];
if (String.IsNullOrEmpty(host))
{
Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(host)));
}
else
{
proxySettings.Host = host;
}
var port = builder["port"];
if (String.IsNullOrEmpty(port))
{
Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(port)));
}
else
{
proxySettings.Port = Int32.Parse(port);
}
//TODO: Setup manualy
var username = builder["username"];
var password = builder["password"];
}
private ProxyClientHandler<Socks5> CreateNewSocks5Client()
{
if(proxySettings.Host == null || proxySettings.Port == 0)
{
throw new Exception("Please add your proxy settings to proxysettings.json!");
}
return new ProxyClientHandler<Socks5>(proxySettings);
}
[Fact]
public void Test1()
{
}
}
}
```
Add base uri to tests | ```c#
using System;
using System.Diagnostics;
using Microsoft.Extensions.Configuration;
using Xunit;
using SocksSharp;
using SocksSharp.Proxy;
namespace SocksSharp.Tests
{
public class ProxyClientTests
{
private Uri baseUri = new Uri("http://httpbin.org/");
private ProxySettings proxySettings;
private void GatherTestConfiguration()
{
var appConfigMsgWarning = "{0} not configured in proxysettings.json! Some tests may fail.";
var builder = new ConfigurationBuilder()
.AddJsonFile("proxysettings.json")
.Build();
proxySettings = new ProxySettings();
var host = builder["host"];
if (String.IsNullOrEmpty(host))
{
Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(host)));
}
else
{
proxySettings.Host = host;
}
var port = builder["port"];
if (String.IsNullOrEmpty(port))
{
Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(port)));
}
else
{
proxySettings.Port = Int32.Parse(port);
}
//TODO: Setup manualy
var username = builder["username"];
var password = builder["password"];
}
private ProxyClientHandler<Socks5> CreateNewSocks5Client()
{
if(proxySettings.Host == null || proxySettings.Port == 0)
{
throw new Exception("Please add your proxy settings to proxysettings.json!");
}
return new ProxyClientHandler<Socks5>(proxySettings);
}
[Fact]
public void Test1()
{
}
}
}
``` |
89fd6670-9c61-4842-8e40-09183476cf56 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel.Composition;
namespace Cogito.Composition
{
/// <summary>
/// Attaches an Order metadata property to the export.
/// </summary>
[MetadataAttribute]
public class ExportOrderAttribute :
Attribute
{
readonly int order;
/// <summary>
/// Initializes a new instance.
/// </summary>
/// <param name="order"></param>
/// <returns></returns>
public ExportOrderAttribute(int order)
{
Priority = order;
}
public int Priority { get; set; }
}
}
```
Check Azure configuration more carefully. Add contracts for some base classes. Fix ExportOrder. | ```c#
using System;
using System.ComponentModel.Composition;
namespace Cogito.Composition
{
/// <summary>
/// Attaches an Order metadata property to the export.
/// </summary>
[MetadataAttribute]
public class ExportOrderAttribute :
Attribute,
IOrderedExportMetadata
{
/// <summary>
/// Initializes a new instance.
/// </summary>
/// <param name="order"></param>
/// <returns></returns>
public ExportOrderAttribute(int order)
{
Order = order;
}
public int Order { get; set; }
}
}
``` |
21558581-de25-4b03-a979-96f61fb70ff9 | {
"language": "C#"
} | ```c#
namespace DarkSky.UnitTests.Extensions
{
using System;
using NodaTime;
using Xunit;
using static DarkSky.Extensions.LongExtensions;
public class LongExtensionsUnitTests
{
public static System.Collections.Generic.IEnumerable<object[]> GetDateTimeOffsets()
{
yield return new object[] { DateTimeOffset.MinValue, "UTC" };
yield return new object[] { DateTimeOffset.MaxValue, "UTC" };
yield return new object[] { new DateTimeOffset(2017, 1, 1, 1, 0, 0, new TimeSpan(0)), "UTC" };
yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), "America/New_York" };
}
[Theory]
[MemberData(nameof(GetDateTimeOffsets))]
public void CorrectConversionTest(DateTimeOffset date, string timezone)
{
// Truncate milliseconds since we don't use them for the UNIX timestamps.
var dateTimeOffset = date.AddTicks(-(date.Ticks % TimeSpan.TicksPerSecond));
var convertedDate = dateTimeOffset.ToUnixTimeSeconds().ToDateTimeOffsetFromUnixTimestamp(timezone);
Assert.Equal(dateTimeOffset, convertedDate);
}
}
}```
Add unit test for empty timezone | ```c#
namespace DarkSky.UnitTests.Extensions
{
using System;
using NodaTime;
using Xunit;
using static DarkSky.Extensions.LongExtensions;
public class LongExtensionsUnitTests
{
public static System.Collections.Generic.IEnumerable<object[]> GetDateTimeOffsets()
{
yield return new object[] { DateTimeOffset.MinValue, "UTC" };
yield return new object[] { DateTimeOffset.MaxValue, "UTC" };
yield return new object[] { new DateTimeOffset(2017, 1, 1, 1, 0, 0, new TimeSpan(0)), "UTC" };
yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), "America/New_York" };
yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), string.Empty };
yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), null };
}
[Theory]
[MemberData(nameof(GetDateTimeOffsets))]
public void CorrectConversionTest(DateTimeOffset date, string timezone)
{
// Truncate milliseconds since we don't use them for the UNIX timestamps.
var dateTimeOffset = date.AddTicks(-(date.Ticks % TimeSpan.TicksPerSecond));
var convertedDate = dateTimeOffset.ToUnixTimeSeconds().ToDateTimeOffsetFromUnixTimestamp(timezone);
Assert.Equal(dateTimeOffset, convertedDate);
}
}
}``` |
170d8509-7084-4c28-8860-0cfc80c53d09 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Screens.Edit.Setup
{
public class SetupScreen : EditorScreen
{
public SetupScreen()
{
Child = new ScreenWhiteBox.UnderConstructionMessage("Setup mode");
}
}
}
```
Add basic setup for song select screen | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterfaceV2;
using osuTK;
namespace osu.Game.Screens.Edit.Setup
{
public class SetupScreen : EditorScreen
{
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Children = new Drawable[]
{
new Box
{
Colour = colours.Gray0,
RelativeSizeAxes = Axes.Both,
},
new OsuScrollContainer
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding(50),
Child = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Spacing = new Vector2(20),
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.X,
Height = 250,
Masking = true,
CornerRadius = 50,
Child = new BeatmapBackgroundSprite(Beatmap.Value)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fill,
},
},
new OsuSpriteText
{
Text = "Beatmap metadata"
},
new LabelledTextBox
{
Label = "Artist",
Current = { Value = Beatmap.Value.Metadata.Artist }
},
new LabelledTextBox
{
Label = "Title",
Current = { Value = Beatmap.Value.Metadata.Title }
},
new LabelledTextBox
{
Label = "Creator",
Current = { Value = Beatmap.Value.Metadata.AuthorString }
},
new LabelledTextBox
{
Label = "Difficulty Name",
Current = { Value = Beatmap.Value.BeatmapInfo.Version }
},
}
},
},
};
}
}
}
``` |
aa40b398-7508-4f76-a3a8-5a64955e8408 | {
"language": "C#"
} | ```c#
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using AutomaticTypeMapper;
using EOLib.IO.Pub;
namespace EOLib.IO.Repositories
{
[MappedType(BaseType = typeof(IPubFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IEIFFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IEIFFileProvider), IsSingleton = true)]
[MappedType(BaseType = typeof(IENFFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IENFFileProvider), IsSingleton = true)]
[MappedType(BaseType = typeof(IESFFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IESFFileProvider), IsSingleton = true)]
[MappedType(BaseType = typeof(IECFFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IECFFileProvider), IsSingleton = true)]
public class PubFileRepository : IPubFileRepository, IPubFileProvider
{
public IPubFile<EIFRecord> EIFFile { get; set; }
public IPubFile<ENFRecord> ENFFile { get; set; }
public IPubFile<ESFRecord> ESFFile { get; set; }
public IPubFile<ECFRecord> ECFFile { get; set; }
}
}```
Fix type mapping for IPubFileProvider | ```c#
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using AutomaticTypeMapper;
using EOLib.IO.Pub;
namespace EOLib.IO.Repositories
{
[MappedType(BaseType = typeof(IPubFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IPubFileProvider), IsSingleton = true)]
[MappedType(BaseType = typeof(IEIFFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IEIFFileProvider), IsSingleton = true)]
[MappedType(BaseType = typeof(IENFFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IENFFileProvider), IsSingleton = true)]
[MappedType(BaseType = typeof(IESFFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IESFFileProvider), IsSingleton = true)]
[MappedType(BaseType = typeof(IECFFileRepository), IsSingleton = true)]
[MappedType(BaseType = typeof(IECFFileProvider), IsSingleton = true)]
public class PubFileRepository : IPubFileRepository, IPubFileProvider
{
public IPubFile<EIFRecord> EIFFile { get; set; }
public IPubFile<ENFRecord> ENFFile { get; set; }
public IPubFile<ESFRecord> ESFFile { get; set; }
public IPubFile<ECFRecord> ECFFile { get; set; }
}
}``` |
1e0bbad6-a842-4bcb-bcea-06824ef02556 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using Wox.Plugin.BrowserBookmark.Commands;
using Wox.Plugin.SharedCommands;
namespace Wox.Plugin.BrowserBookmark
{
public class Main : IPlugin
{
private PluginInitContext context;
private List<Bookmark> cachedBookmarks = new List<Bookmark>();
public void Init(PluginInitContext context)
{
this.context = context;
cachedBookmarks = Bookmarks.LoadAllBookmarks();
}
public List<Result> Query(Query query)
{
string param = query.GetAllRemainingParameter().TrimStart();
// Should top results be returned? (true if no search parameters have been passed)
var topResults = string.IsNullOrEmpty(param);
var returnList = cachedBookmarks;
if (!topResults)
{
// Since we mixed chrome and firefox bookmarks, we should order them again
returnList = cachedBookmarks.Where(o => Bookmarks.MatchProgram(o, param)).ToList();
returnList = returnList.OrderByDescending(o => o.Score).ToList();
}
return returnList.Select(c => new Result()
{
Title = c.Name,
SubTitle = "Bookmark: " + c.Url,
IcoPath = @"Images\bookmark.png",
Score = 5,
Action = (e) =>
{
context.API.HideApp();
c.Url.NewBrowserWindow("");
return true;
}
}).ToList();
}
}
}
```
Add IReloadable interface and method | ```c#
using System.Collections.Generic;
using System.Linq;
using Wox.Plugin.BrowserBookmark.Commands;
using Wox.Plugin.SharedCommands;
namespace Wox.Plugin.BrowserBookmark
{
public class Main : IPlugin, IReloadable
{
private PluginInitContext context;
private List<Bookmark> cachedBookmarks = new List<Bookmark>();
public void Init(PluginInitContext context)
{
this.context = context;
cachedBookmarks = Bookmarks.LoadAllBookmarks();
}
public List<Result> Query(Query query)
{
string param = query.GetAllRemainingParameter().TrimStart();
// Should top results be returned? (true if no search parameters have been passed)
var topResults = string.IsNullOrEmpty(param);
var returnList = cachedBookmarks;
if (!topResults)
{
// Since we mixed chrome and firefox bookmarks, we should order them again
returnList = cachedBookmarks.Where(o => Bookmarks.MatchProgram(o, param)).ToList();
returnList = returnList.OrderByDescending(o => o.Score).ToList();
}
return returnList.Select(c => new Result()
{
Title = c.Name,
SubTitle = "Bookmark: " + c.Url,
IcoPath = @"Images\bookmark.png",
Score = 5,
Action = (e) =>
{
context.API.HideApp();
c.Url.NewBrowserWindow("");
return true;
}
}).ToList();
}
public void ReloadData()
{
cachedBookmarks.Clear();
cachedBookmarks = Bookmarks.LoadAllBookmarks();
}
}
}
``` |
f51f9003-66fe-4dec-bb4d-6efc7db023ab | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Skylight")]
[assembly: AssemblyDescription("An API by TakoMan02 for Everybody Edits")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TakoMan02")]
[assembly: AssemblyProduct("Skylight")]
[assembly: AssemblyCopyright("Copyright © TakoMan02 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Skylight")]
[assembly: ComVisible(false)]
[assembly: Guid("a460c245-2753-4861-ae17-751db86fbae2")]
//
//
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("0.0.5.0")]```
Change version number to v0.5.1.0 | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Skylight")]
[assembly: AssemblyDescription("An API by TakoMan02 for Everybody Edits")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TakoMan02")]
[assembly: AssemblyProduct("Skylight")]
[assembly: AssemblyCopyright("Copyright © TakoMan02 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Skylight")]
[assembly: ComVisible(false)]
[assembly: Guid("a460c245-2753-4861-ae17-751db86fbae2")]
//
//
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("0.5.1.0")]``` |
fa1098df-3cc4-4d68-a0bd-376008bdacd4 | {
"language": "C#"
} | ```c#
using System;
namespace SQLite.Net
{
public class BlobSerializerDelegate : IBlobSerializer
{
public delegate byte[] SerializeDelegate(object obj);
public delegate bool CanSerializeDelegate(Type type);
public delegate object DeserializeDelegate(byte[] data, Type type);
private readonly SerializeDelegate serializeDelegate;
private readonly DeserializeDelegate deserializeDelegate;
private readonly CanSerializeDelegate canDeserializeDelegate;
public BlobSerializerDelegate (SerializeDelegate serializeDelegate,
DeserializeDelegate deserializeDelegate,
CanSerializeDelegate canDeserializeDelegate)
{
this.serializeDelegate = serializeDelegate;
this.deserializeDelegate = deserializeDelegate;
this.canDeserializeDelegate = canDeserializeDelegate;
}
#region IBlobSerializer implementation
public byte[] Serialize<T>(T obj)
{
return this.serializeDelegate (obj);
}
public object Deserialize(byte[] data, Type type)
{
return this.deserializeDelegate (data, type);
}
public bool CanDeserialize(Type type)
{
return this.canDeserializeDelegate (type);
}
#endregion
}
}
```
Rename fields name pattern to match rest of code | ```c#
using System;
namespace SQLite.Net
{
public class BlobSerializerDelegate : IBlobSerializer
{
public delegate byte[] SerializeDelegate(object obj);
public delegate bool CanSerializeDelegate(Type type);
public delegate object DeserializeDelegate(byte[] data, Type type);
private readonly SerializeDelegate _serializeDelegate;
private readonly DeserializeDelegate _deserializeDelegate;
private readonly CanSerializeDelegate _canDeserializeDelegate;
public BlobSerializerDelegate(SerializeDelegate serializeDelegate,
DeserializeDelegate deserializeDelegate,
CanSerializeDelegate canDeserializeDelegate)
{
_serializeDelegate = serializeDelegate;
_deserializeDelegate = deserializeDelegate;
_canDeserializeDelegate = canDeserializeDelegate;
}
#region IBlobSerializer implementation
public byte[] Serialize<T>(T obj)
{
return _serializeDelegate(obj);
}
public object Deserialize(byte[] data, Type type)
{
return _deserializeDelegate(data, type);
}
public bool CanDeserialize(Type type)
{
return _canDeserializeDelegate(type);
}
#endregion
}
}``` |
bbeb0987-5bb1-45eb-bfb0-98f513f3f9e5 | {
"language": "C#"
} | ```c#
using Cake.Core.IO;
using Ensconce.Update;
using System.IO;
namespace Ensconce.Cake
{
public static class EnsconceFileUpdateExtensions
{
public static void TextSubstitute(this IFile file, FilePath fixedStructureFile)
{
var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath);
Update.ProcessFiles.UpdateFile(new FileInfo(file.Path.FullPath), tagDictionary);
}
public static void TextSubstitute(this IDirectory directory, FilePath fixedStructureFile)
{
directory.TextSubstitute("*.*", fixedStructureFile);
}
public static void TextSubstitute(this IDirectory directory, string filter, FilePath fixedStructureFile)
{
var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath);
Update.ProcessFiles.UpdateFiles(directory.Path.FullPath, filter, tagDictionary);
}
}
}
```
Handle update based on a path object as well as the directory/file | ```c#
using Cake.Core.IO;
using Ensconce.Update;
using System.IO;
namespace Ensconce.Cake
{
public static class EnsconceFileUpdateExtensions
{
public static void TextSubstitute(this IFile file, FilePath fixedStructureFile)
{
file.Path.TextSubstitute(fixedStructureFile);
}
public static void TextSubstitute(this IDirectory directory, FilePath fixedStructureFile)
{
directory.Path.TextSubstitute(fixedStructureFile);
}
public static void TextSubstitute(this IDirectory directory, string filter, FilePath fixedStructureFile)
{
directory.Path.TextSubstitute(filter, fixedStructureFile);
}
public static void TextSubstitute(this FilePath file, FilePath fixedStructureFile)
{
var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath);
Update.ProcessFiles.UpdateFile(new FileInfo(file.FullPath), tagDictionary);
}
public static void TextSubstitute(this DirectoryPath directory, FilePath fixedStructureFile)
{
directory.TextSubstitute("*.*", fixedStructureFile);
}
public static void TextSubstitute(this DirectoryPath directory, string filter, FilePath fixedStructureFile)
{
var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath);
Update.ProcessFiles.UpdateFiles(directory.FullPath, filter, tagDictionary);
}
}
}
``` |
67fe712b-23e7-4909-ab10-f17d11ef5f52 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using BForms.Models;
using BForms.Mvc;
namespace BForms.Docs
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//register BForms validation provider
ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider());
BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager);
//BForms.Utilities.BsUIManager.Theme(BsTheme.Black);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
#if !DEBUG
BForms.Utilities.BsConfigurationManager.Release(true);
#endif
}
}
}
```
Revert "fixed mandatory field error message" | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using BForms.Models;
using BForms.Mvc;
namespace BForms.Docs
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//register BForms validation provider
ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider());
BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager);
//BForms.Utilities.BsUIManager.Theme(BsTheme.Black);
#if !DEBUG
BForms.Utilities.BsConfigurationManager.Release(true);
#endif
}
}
}
``` |
10075adb-ab76-4fc9-99bc-b016af4cbf57 | {
"language": "C#"
} | ```c#
namespace ServiceStack.Common.Web
{
public static class HttpHeaders
{
public const string XParamOverridePrefix = "X-Param-Override-";
public const string XHttpMethodOverride = "X-Http-Method-Override";
public const string XUserAuthId = "X-UAId";
public const string XForwardedFor = "X-Forwarded-For";
public const string XRealIp = "X-Real-IP";
public const string Referer = "Referer";
public const string CacheControl = "Cache-Control";
public const string IfModifiedSince = "If-Modified-Since";
public const string LastModified = "Last-Modified";
public const string Accept = "Accept";
public const string AcceptEncoding = "Accept-Encoding";
public const string ContentType = "Content-Type";
public const string ContentEncoding = "Content-Encoding";
public const string ContentLength = "Content-Length";
public const string ContentDisposition = "Content-Disposition";
public const string Location = "Location";
public const string SetCookie = "Set-Cookie";
public const string ETag = "ETag";
public const string Authorization = "Authorization";
public const string WwwAuthenticate = "WWW-Authenticate";
public const string AllowOrigin = "Access-Control-Allow-Origin";
public const string AllowMethods = "Access-Control-Allow-Methods";
public const string AllowHeaders = "Access-Control-Allow-Headers";
public const string AllowCredentials = "Access-Control-Allow-Credentials";
}
}```
Add a const string field for the If-None-Match HTTP header | ```c#
namespace ServiceStack.Common.Web
{
public static class HttpHeaders
{
public const string XParamOverridePrefix = "X-Param-Override-";
public const string XHttpMethodOverride = "X-Http-Method-Override";
public const string XUserAuthId = "X-UAId";
public const string XForwardedFor = "X-Forwarded-For";
public const string XRealIp = "X-Real-IP";
public const string Referer = "Referer";
public const string CacheControl = "Cache-Control";
public const string IfModifiedSince = "If-Modified-Since";
public const string IfNoneMatch = "If-None-Match";
public const string LastModified = "Last-Modified";
public const string Accept = "Accept";
public const string AcceptEncoding = "Accept-Encoding";
public const string ContentType = "Content-Type";
public const string ContentEncoding = "Content-Encoding";
public const string ContentLength = "Content-Length";
public const string ContentDisposition = "Content-Disposition";
public const string Location = "Location";
public const string SetCookie = "Set-Cookie";
public const string ETag = "ETag";
public const string Authorization = "Authorization";
public const string WwwAuthenticate = "WWW-Authenticate";
public const string AllowOrigin = "Access-Control-Allow-Origin";
public const string AllowMethods = "Access-Control-Allow-Methods";
public const string AllowHeaders = "Access-Control-Allow-Headers";
public const string AllowCredentials = "Access-Control-Allow-Credentials";
}
}``` |
7e72e857-efae-4d48-b7bb-984b8fec054e | {
"language": "C#"
} | ```c#
using Nito.AsyncEx;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Extensions.Caching.Memory
{
public static class MemoryExtensions
{
private static Dictionary<object, AsyncLock> AsyncLocks { get; } = new Dictionary<object, AsyncLock>();
private static object AsyncLocksLock { get; } = new object();
public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory)
{
if (cache.TryGetValue(key, out TItem value))
{
return value;
}
AsyncLock asyncLock;
lock (AsyncLocksLock)
{
if (!AsyncLocks.TryGetValue(key, out asyncLock))
{
asyncLock = new AsyncLock();
AsyncLocks.Add(key, asyncLock);
}
}
using (await asyncLock.LockAsync().ConfigureAwait(false))
{
if (!cache.TryGetValue(key, out value))
{
value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false);
}
return value;
}
}
}
}
```
Make sure to clean my dic. | ```c#
using Nito.AsyncEx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Extensions.Caching.Memory
{
public static class MemoryExtensions
{
private static Dictionary<object, AsyncLock> AsyncLocks { get; } = new Dictionary<object, AsyncLock>();
private static object AsyncLocksLock { get; } = new object();
public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory)
{
if (cache.TryGetValue(key, out TItem value))
{
return value;
}
AsyncLock asyncLock;
lock (AsyncLocksLock)
{
// Cleanup the evicted asynclocks first.
foreach (var toRemove in AsyncLocks.Keys.Where(x => !cache.TryGetValue(x, out _)).ToList())
{
AsyncLocks.Remove(toRemove);
}
if (!AsyncLocks.TryGetValue(key, out asyncLock))
{
asyncLock = new AsyncLock();
AsyncLocks.Add(key, asyncLock);
}
}
using (await asyncLock.LockAsync().ConfigureAwait(false))
{
if (!cache.TryGetValue(key, out value))
{
value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false);
}
return value;
}
}
}
}
``` |
cb637973-9517-4f76-a678-77f5308b50fd | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.Web")]
[assembly: AssemblyDescription("")]
```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.Web")]
``` |
3c5fa242-4f91-4fa4-83ae-e1af53d4e36d | {
"language": "C#"
} | ```c#
using System;
namespace XeroApi.Model
{
public class Journal : EndpointModelBase
{
[ItemId]
public Guid JournalID { get; set; }
public DateTime JournalDate { get; set; }
public long JournalNumber { get; set; }
[ItemUpdatedDate]
public DateTime CreatedDateUTC { get; set; }
public string Reference { get; set; }
public JournalLines JournalLines { get; set; }
public override string ToString()
{
return string.Format("Journal:{0}", JournalNumber);
}
}
public class Journals : ModelList<Journal>
{
}
}
```
Add SourceID and SourceType to journal | ```c#
using System;
namespace XeroApi.Model
{
public class Journal : EndpointModelBase
{
[ItemId]
public Guid JournalID { get; set; }
public DateTime JournalDate { get; set; }
public long JournalNumber { get; set; }
[ItemUpdatedDate]
public DateTime CreatedDateUTC { get; set; }
public string Reference { get; set; }
public JournalLines JournalLines { get; set; }
public Guid SourceID { get; set; }
public string SourceType { get; set; }
public override string ToString()
{
return string.Format("Journal:{0}", JournalNumber);
}
}
public class Journals : ModelList<Journal>
{
}
}
``` |
cbefdf17-0669-42d2-b814-06ced404e200 | {
"language": "C#"
} | ```c#
using System;
using System.Configuration;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace TrackableData.MySql.Tests
{
public class Database : IDisposable
{
public Database()
{
var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
// create TestDb if not exist
var cstrForMaster = "";
{
var connectionBuilder = new SqlConnectionStringBuilder(cstr);
connectionBuilder.InitialCatalog = "sys";
cstrForMaster = connectionBuilder.ToString();
}
using (var conn = new MySqlConnection(cstrForMaster))
{
conn.Open();
using (var cmd = new MySqlCommand())
{
cmd.CommandText = string.Format(@"
DROP DATABASE IF EXISTS {0};
CREATE DATABASE {0};
", new SqlConnectionStringBuilder(cstr).InitialCatalog);
cmd.Connection = conn;
var result = cmd.ExecuteScalar();
}
}
}
public MySqlConnection Connection
{
get
{
var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
var connection = new MySqlConnection(cstr);
connection.Open();
return connection;
}
}
public void Dispose()
{
}
}
}
```
Fix bug to find non-existent sys db in mysql | ```c#
using System;
using System.Configuration;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace TrackableData.MySql.Tests
{
public class Database : IDisposable
{
public Database()
{
var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
// create TestDb if not exist
var cstrForMaster = "";
{
var connectionBuilder = new SqlConnectionStringBuilder(cstr);
connectionBuilder.InitialCatalog = "";
cstrForMaster = connectionBuilder.ToString();
}
using (var conn = new MySqlConnection(cstrForMaster))
{
conn.Open();
using (var cmd = new MySqlCommand())
{
cmd.CommandText = string.Format(@"
DROP DATABASE IF EXISTS {0};
CREATE DATABASE {0};
", new SqlConnectionStringBuilder(cstr).InitialCatalog);
cmd.Connection = conn;
var result = cmd.ExecuteScalar();
}
}
}
public MySqlConnection Connection
{
get
{
var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
var connection = new MySqlConnection(cstr);
connection.Open();
return connection;
}
}
public void Dispose()
{
}
}
}
``` |
d90356c2-73aa-4e8b-bbf2-48cd376eefb2 | {
"language": "C#"
} | ```c#
namespace Certify.Models.Config
{
public class ActionResult
{
public ActionResult() { }
public ActionResult(string msg, bool isSuccess)
{
Message = msg;
IsSuccess = isSuccess;
}
public bool IsSuccess { get; set; }
public string Message { get; set; }
/// <summary>
/// Optional field to hold related information such as required info or error details
/// </summary>
public object Result { get; set; }
}
public class ActionResult<T> : ActionResult
{
public new T Result;
public ActionResult() { }
public ActionResult(string msg, bool isSuccess)
{
Message = msg;
IsSuccess = isSuccess;
}
public ActionResult(string msg, bool isSuccess, T result)
{
Message = msg;
IsSuccess = isSuccess;
Result = result;
}
}
}
```
Add IsWarning to action result | ```c#
namespace Certify.Models.Config
{
public class ActionResult
{
public ActionResult() { }
public ActionResult(string msg, bool isSuccess)
{
Message = msg;
IsSuccess = isSuccess;
}
public bool IsSuccess { get; set; }
public bool IsWarning { get; set; }
public string Message { get; set; }
/// <summary>
/// Optional field to hold related information such as required info or error details
/// </summary>
public object Result { get; set; }
}
public class ActionResult<T> : ActionResult
{
public new T Result;
public ActionResult() { }
public ActionResult(string msg, bool isSuccess)
{
Message = msg;
IsSuccess = isSuccess;
}
public ActionResult(string msg, bool isSuccess, T result)
{
Message = msg;
IsSuccess = isSuccess;
Result = result;
}
}
}
``` |
82c62248-2947-47d0-8933-99fe5692fbe1 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Frosting;
public static class Program
{
public static int Main(string[] args)
{
return new CakeHost()
.UseContext<BuildContext>()
.UseWorkingDirectory("..")
.Run(args);
}
}
public class BuildContext : FrostingContext
{
public bool Delay { get; set; }
public BuildContext(ICakeContext context)
: base(context)
{
Delay = context.Arguments.HasArgument("delay");
}
}
[TaskName("Hello")]
public sealed class HelloTask : FrostingTask<BuildContext>
{
public override void Run(BuildContext context)
{
context.Log.Information("Hello");
}
}
[TaskName("World")]
[IsDependentOn(typeof(HelloTask))]
public sealed class WorldTask : AsyncFrostingTask<BuildContext>
{
// Tasks can be asynchronous
public override async Task RunAsync(BuildContext context)
{
if (context.Delay)
{
context.Log.Information("Waiting...");
await Task.Delay(1500);
}
context.Log.Information("World");
}
}
[TaskName("Default")]
[IsDependentOn(typeof(WorldTask))]
public class DefaultTask : FrostingTask
{
}```
Remove use of UseWorkingDirectory in default template | ```c#
using System.Threading.Tasks;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Frosting;
public static class Program
{
public static int Main(string[] args)
{
return new CakeHost()
.UseContext<BuildContext>()
.Run(args);
}
}
public class BuildContext : FrostingContext
{
public bool Delay { get; set; }
public BuildContext(ICakeContext context)
: base(context)
{
Delay = context.Arguments.HasArgument("delay");
}
}
[TaskName("Hello")]
public sealed class HelloTask : FrostingTask<BuildContext>
{
public override void Run(BuildContext context)
{
context.Log.Information("Hello");
}
}
[TaskName("World")]
[IsDependentOn(typeof(HelloTask))]
public sealed class WorldTask : AsyncFrostingTask<BuildContext>
{
// Tasks can be asynchronous
public override async Task RunAsync(BuildContext context)
{
if (context.Delay)
{
context.Log.Information("Waiting...");
await Task.Delay(1500);
}
context.Log.Information("World");
}
}
[TaskName("Default")]
[IsDependentOn(typeof(WorldTask))]
public class DefaultTask : FrostingTask
{
}``` |
3fe522e8-fde3-4da7-b431-ac2791bde7d4 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Upgrade {
NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD
}
```
Add other upgrades to enum | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Upgrade {
NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD, BEEBALL, SCHOOLBUZZ, BUZZFEED, BEACH, GUM, VISOR
}
``` |
c2efd0a9-8944-436a-baf0-4b3ed7cbe9e2 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Newtonsoft.Json.Serialization;
namespace Swashbuckle.Swagger
{
public static class JsonPropertyExtensions
{
public static bool IsRequired(this JsonProperty jsonProperty)
{
return jsonProperty.HasAttribute<RequiredAttribute>();
}
public static bool IsObsolete(this JsonProperty jsonProperty)
{
return jsonProperty.HasAttribute<ObsoleteAttribute>();
}
public static bool HasAttribute<T>(this JsonProperty jsonProperty)
{
var propInfo = jsonProperty.PropertyInfo();
return propInfo != null && Attribute.IsDefined(propInfo, typeof (T));
}
public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty)
{
if(jsonProperty.UnderlyingName == null) return null;
return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType);
}
}
}
```
Fix to also check the Required property of the JsonProperty when determining if a model property is required or optional. | ```c#
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Swashbuckle.Swagger
{
public static class JsonPropertyExtensions
{
public static bool IsRequired(this JsonProperty jsonProperty)
{
return jsonProperty.HasAttribute<RequiredAttribute>() || jsonProperty.Required == Required.Always;
}
public static bool IsObsolete(this JsonProperty jsonProperty)
{
return jsonProperty.HasAttribute<ObsoleteAttribute>();
}
public static bool HasAttribute<T>(this JsonProperty jsonProperty)
{
var propInfo = jsonProperty.PropertyInfo();
return propInfo != null && Attribute.IsDefined(propInfo, typeof (T));
}
public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty)
{
if(jsonProperty.UnderlyingName == null) return null;
return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType);
}
}
}
``` |
4cb0c73c-3119-47e5-8a52-9e4636707a84 | {
"language": "C#"
} | ```c#
using Microsoft.Extensions.Configuration;
using Xunit;
namespace RedditSharpTests
{
public class AuthenticatedTestsFixture
{
public IConfigurationRoot Config { get; private set; }
public string AccessToken { get; private set; }
public RedditSharp.BotWebAgent WebAgent { get; set; }
public string TestUserName { get; private set; }
public AuthenticatedTestsFixture()
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile("private.config")
.AddEnvironmentVariables();
Config = builder.Build();
WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]);
AccessToken = WebAgent.AccessToken;
TestUserName = Config["TestUserName"];
}
}
[CollectionDefinition("AuthenticatedTests")]
public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
}
```
Set private.config to optional to fix unit tests on build server | ```c#
using Microsoft.Extensions.Configuration;
using Xunit;
namespace RedditSharpTests
{
public class AuthenticatedTestsFixture
{
public IConfigurationRoot Config { get; private set; }
public string AccessToken { get; private set; }
public RedditSharp.BotWebAgent WebAgent { get; set; }
public string TestUserName { get; private set; }
public AuthenticatedTestsFixture()
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile("private.config",true)
.AddEnvironmentVariables();
Config = builder.Build();
WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]);
AccessToken = WebAgent.AccessToken;
TestUserName = Config["TestUserName"];
}
}
[CollectionDefinition("AuthenticatedTests")]
public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
}
``` |
f6684360-3dbb-4ff5-adf2-6db116e0ebf0 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct ServerTimeMessage : INetSerializable
{
public int serverUnixTime;
public float serverTime;
public void Deserialize(NetDataReader reader)
{
serverUnixTime = reader.GetInt();
serverTime = reader.GetFloat();
}
public void Serialize(NetDataWriter writer)
{
writer.Put(serverUnixTime);
writer.Put(serverTime);
}
}
}
```
Reduce packet size, remove bloated time codes | ```c#
using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct ServerTimeMessage : INetSerializable
{
public int serverUnixTime;
public void Deserialize(NetDataReader reader)
{
serverUnixTime = reader.GetPackedInt();
}
public void Serialize(NetDataWriter writer)
{
writer.PutPackedInt(serverUnixTime);
}
}
}
``` |
e7e97398-c150-443d-bd45-9dc711c2dd2e | {
"language": "C#"
} | ```c#
// Needed for Workaround
using System;
using System.Threading;
using Theraot.Collections.ThreadSafe;
namespace Theraot.Threading
{
public static partial class GCMonitor
{
private static class Internal
{
private static readonly WeakDelegateCollection _collectedEventHandlers;
private static readonly WaitCallback work;
static Internal()
{
work = _ => RaiseCollected();
_collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint);
}
public static WeakDelegateCollection CollectedEventHandlers
{
get
{
return _collectedEventHandlers;
}
}
public static void Invoke()
{
ThreadPool.QueueUserWorkItem(work);
}
private static void RaiseCollected()
{
var check = Thread.VolatileRead(ref _status);
if (check == INT_StatusReady)
{
try
{
_collectedEventHandlers.RemoveDeadItems();
_collectedEventHandlers.Invoke(null, new EventArgs());
}
catch (Exception exception)
{
// Pokemon
GC.KeepAlive(exception);
}
Thread.VolatileWrite(ref _status, INT_StatusReady);
}
}
}
}
}```
Rename refactor;: GCMonitor.work -> GCMonitor._work | ```c#
// Needed for Workaround
using System;
using System.Threading;
using Theraot.Collections.ThreadSafe;
namespace Theraot.Threading
{
public static partial class GCMonitor
{
private static class Internal
{
private static readonly WeakDelegateCollection _collectedEventHandlers;
private static readonly WaitCallback _work;
static Internal()
{
_work = _ => RaiseCollected();
_collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint);
}
public static WeakDelegateCollection CollectedEventHandlers
{
get
{
return _collectedEventHandlers;
}
}
public static void Invoke()
{
ThreadPool.QueueUserWorkItem(_work);
}
private static void RaiseCollected()
{
var check = Thread.VolatileRead(ref _status);
if (check == INT_StatusReady)
{
try
{
_collectedEventHandlers.RemoveDeadItems();
_collectedEventHandlers.Invoke(null, new EventArgs());
}
catch (Exception exception)
{
// Pokemon
GC.KeepAlive(exception);
}
Thread.VolatileWrite(ref _status, INT_StatusReady);
}
}
}
}
}``` |
4da45b65-8fe3-4a9b-aa6c-a1acee9ae875 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
/**
* Dealing with raw touch input from a Cardboard device
*/
public class ParsedTouchData {
private bool wasTouched = false;
public ParsedTouchData() {}
public void Update() {
wasTouched |= this.IsDown();
}
public bool IsDown() {
return Input.touchCount > 0;
}
public bool IsUp() {
if (!this.IsDown() && wasTouched) {
wasTouched = false;
return true;
}
return false;
}
}
```
Update for new version of Cardboard SDK | ```c#
using UnityEngine;
using System.Collections;
/**
* Dealing with raw touch input from a Cardboard device
*/
public class ParsedTouchData {
private bool wasTouched = false;
public ParsedTouchData() {
Cardboard cardboard = CardboardGameObject().GetComponent<Cardboard>();
cardboard.TapIsTrigger = false;
}
private GameObject CardboardGameObject() {
GameObject gameObject = Camera.main.gameObject;
return gameObject.transform.parent.parent.gameObject;
}
public void Update() {
wasTouched |= IsDown();
}
public bool IsDown() {
return Input.touchCount > 0;
}
public bool IsUp() {
if (!IsDown() && wasTouched) {
wasTouched = false;
return true;
}
return false;
}
}
``` |
2ca73c5d-28fa-4e48-8e81-5a4fc535f77c | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
namespace BTCPayServer.Security;
public class AuthorizationFilterHandle
{
public AuthorizationHandlerContext Context { get; }
public PolicyRequirement Requirement { get; }
public HttpContext HttpContext { get; }
public bool Success { get; }
public AuthorizationFilterHandle(
AuthorizationHandlerContext context,
PolicyRequirement requirement,
HttpContext httpContext)
{
Context = context;
Requirement = requirement;
HttpContext = httpContext;
}
}
```
Add ability to mark auth handle as successful | ```c#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
namespace BTCPayServer.Security;
public class AuthorizationFilterHandle
{
public AuthorizationHandlerContext Context { get; }
public PolicyRequirement Requirement { get; }
public HttpContext HttpContext { get; }
public bool Success { get; private set; }
public AuthorizationFilterHandle(
AuthorizationHandlerContext context,
PolicyRequirement requirement,
HttpContext httpContext)
{
Context = context;
Requirement = requirement;
HttpContext = httpContext;
}
public void MarkSuccessful()
{
Success = true;
}
}
``` |
1b4a124d-5774-41b9-990f-d4e736818fc3 | {
"language": "C#"
} | ```c#
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2009 Jason Booth
Copyright (c) 2011-2012 openxlive.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
namespace CocosSharp
{
public interface ICCSAXDelegator
{
void StartElement(object ctx, string name, string[] atts);
void EndElement(object ctx, string name);
void TextHandler(object ctx, byte[] ch, int len);
}
}```
Mark ICCSaxDelegator class as internal. | ```c#
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2009 Jason Booth
Copyright (c) 2011-2012 openxlive.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
namespace CocosSharp
{
internal interface ICCSAXDelegator
{
void StartElement(object ctx, string name, string[] atts);
void EndElement(object ctx, string name);
void TextHandler(object ctx, byte[] ch, int len);
}
}``` |
90311579-e6bd-47cc-b940-b2a1ed2bb3a9 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace BoardGamesApi.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class TempController : Controller
{
private readonly IConfiguration _configuration;
public TempController(IConfiguration configuration)
{
_configuration = configuration;
}
[AllowAnonymous]
[Route("/get-token")]
public IActionResult GenerateToken(string name = "mscommunity")
{
var jwt = JwtTokenGenerator
.Generate(name, true, _configuration["Token:Issuer"], _configuration["Token:Key"]);
return Ok(jwt);
}
}
}
```
Fix the issue with settings name | ```c#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace BoardGamesApi.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class TempController : Controller
{
private readonly IConfiguration _configuration;
public TempController(IConfiguration configuration)
{
_configuration = configuration;
}
[AllowAnonymous]
[Route("/get-token")]
public IActionResult GenerateToken(string name = "mscommunity")
{
var jwt = JwtTokenGenerator
.Generate(name, true, _configuration["Tokens:Issuer"], _configuration["Tokens:Key"]);
return Ok(jwt);
}
}
}
``` |
e9ae10c0-c100-440d-882b-a7be8ee0bd4a | {
"language": "C#"
} | ```c#
using Eto.Forms;
using MonoMac.AppKit;
using Eto.Drawing;
namespace Eto.Mac.Forms.Controls
{
public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler
where TControl: NSButton
where TWidget: Control
where TCallback: Control.ICallback
{
public virtual string Text
{
get
{
return Control.Title;
}
set
{
var oldSize = GetPreferredSize(Size.MaxValue);
Control.SetTitleWithMnemonic(value);
LayoutIfNeeded(oldSize);
}
}
}
}
```
Allow Button.Text to be set to null | ```c#
using Eto.Forms;
using MonoMac.AppKit;
using Eto.Drawing;
namespace Eto.Mac.Forms.Controls
{
public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler
where TControl: NSButton
where TWidget: Control
where TCallback: Control.ICallback
{
public virtual string Text
{
get
{
return Control.Title;
}
set
{
var oldSize = GetPreferredSize(Size.MaxValue);
Control.SetTitleWithMnemonic(value ?? string.Empty);
LayoutIfNeeded(oldSize);
}
}
}
}
``` |
bf0621f3-8b7d-4995-8fec-95748d0b0d44 | {
"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.ComponentModel;
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Mania
{
public class ManiaInputManager : RulesetInputManager<ManiaAction>
{
public ManiaInputManager(RulesetInfo ruleset, int variant)
: base(ruleset, variant, SimultaneousBindingMode.Unique)
{
}
}
public enum ManiaAction
{
[Description("Special")]
Special,
[Description("Special")]
Specia2,
[Description("Key 1")]
Key1 = 10,
[Description("Key 2")]
Key2,
[Description("Key 3")]
Key3,
[Description("Key 4")]
Key4,
[Description("Key 5")]
Key5,
[Description("Key 6")]
Key6,
[Description("Key 7")]
Key7,
[Description("Key 8")]
Key8,
[Description("Key 9")]
Key9
}
}
```
Increase the point at which normal keys start in ManiaAction | ```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.ComponentModel;
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Mania
{
public class ManiaInputManager : RulesetInputManager<ManiaAction>
{
public ManiaInputManager(RulesetInfo ruleset, int variant)
: base(ruleset, variant, SimultaneousBindingMode.Unique)
{
}
}
public enum ManiaAction
{
[Description("Special")]
Special,
[Description("Special")]
Specia2,
[Description("Key 1")]
Key1 = 1000,
[Description("Key 2")]
Key2,
[Description("Key 3")]
Key3,
[Description("Key 4")]
Key4,
[Description("Key 5")]
Key5,
[Description("Key 6")]
Key6,
[Description("Key 7")]
Key7,
[Description("Key 8")]
Key8,
[Description("Key 9")]
Key9
}
}
``` |
11e80612-0aa9-4d46-8835-048c79c917b5 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using Octokit;
using Rackspace.Threading;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
class LoadingView : Subview
{
private static readonly Vector2 viewSize = new Vector2(300, 250);
private bool isBusy;
private const string WindowTitle = "Loading...";
private const string Header = "";
public override void InitializeView(IView parent)
{
base.InitializeView(parent);
Title = WindowTitle;
Size = viewSize;
}
public override void OnGUI()
{}
public override bool IsBusy
{
get { return false; }
}
}
}
```
Remove unused field, for now | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using Octokit;
using Rackspace.Threading;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
class LoadingView : Subview
{
private static readonly Vector2 viewSize = new Vector2(300, 250);
private const string WindowTitle = "Loading...";
private const string Header = "";
public override void InitializeView(IView parent)
{
base.InitializeView(parent);
Title = WindowTitle;
Size = viewSize;
}
public override void OnGUI()
{}
public override bool IsBusy
{
get { return false; }
}
}
}
``` |
2971a609-5024-453a-96f2-1ba1fa2cac5c | {
"language": "C#"
} | ```c#
using System;
using Xamarin.Forms;
using Xamarin.Forms.OAuth;
namespace OAuthTestApp
{
public class ResultPage : ContentPage
{
public ResultPage(AuthenticatonResult result, Action returnCallback)
{
var stack = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
if (result)
{
stack.Children.Add(new Label
{
Text = $"Provider: {result.Account.Provider}"
});
stack.Children.Add(new Label
{
Text = $"Id: {result.Account.Id}"
});
stack.Children.Add(new Label
{
Text = $"Name: {result.Account.DisplayName}"
});
stack.Children.Add(new Label
{
Text = $"Access Token: {result.Account.AccessToken}"
});
}
else
{
stack.Children.Add(new Label
{
Text = "Authentication failed!"
});
stack.Children.Add(new Label
{
Text = $"Reason: {result.ErrorMessage}"
});
}
stack.Children.Add(new Button
{
Text = "Back",
Command = new Command(returnCallback)
});
Content = stack;
}
}
}
```
Handle physical back button in result view | ```c#
using System;
using Xamarin.Forms;
using Xamarin.Forms.OAuth;
using Xamarin.Forms.OAuth.Views;
namespace OAuthTestApp
{
public class ResultPage : ContentPage, IBackHandlingView
{
private readonly Action _returnCallback;
public ResultPage(AuthenticatonResult result, Action returnCallback)
{
_returnCallback = returnCallback;
var stack = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
if (result)
{
stack.Children.Add(new Label
{
Text = $"Provider: {result.Account.Provider}"
});
stack.Children.Add(new Label
{
Text = $"Id: {result.Account.Id}"
});
stack.Children.Add(new Label
{
Text = $"Name: {result.Account.DisplayName}"
});
stack.Children.Add(new Label
{
Text = $"Access Token: {result.Account.AccessToken}"
});
}
else
{
stack.Children.Add(new Label
{
Text = "Authentication failed!"
});
stack.Children.Add(new Label
{
Text = $"Reason: {result.ErrorMessage}"
});
}
stack.Children.Add(new Button
{
Text = "Back",
Command = new Command(returnCallback)
});
Content = stack;
}
public void HandleBack()
{
_returnCallback?.Invoke();
}
}
}
``` |
f2561c60-d8f6-4985-bba7-9c5e48f6dfeb | {
"language": "C#"
} | ```c#
using Sync.Command;
using Sync.MessageFilter;
using Sync.Plugins;
using Sync.Source;
using Sync.Tools;
using System;
using System.Diagnostics;
using static Sync.Tools.IO;
namespace Sync
{
public static class Program
{
//public static I18n i18n;
static void Main(string[] args)
{
/* 程序工作流程:
* 1.程序枚举所有插件,保存所有IPlugin到List中
* 2.程序整理出所有的List<ISourceBase>
* 3.初始化Sync类,Sync类检测配置文件,用正确的类初始化SyncInstance
* 4.程序IO Manager开始工作,等待用户输入
*/
I18n.Instance.ApplyLanguage(new DefaultI18n());
while(true)
{
SyncHost.Instance = new SyncHost();
SyncHost.Instance.Load();
CurrentIO.WriteWelcome();
string cmd = CurrentIO.ReadCommand();
while (true)
{
SyncHost.Instance.Commands.invokeCmdString(cmd);
cmd = CurrentIO.ReadCommand();
}
}
}
}
}
```
Move input block for thread safe | ```c#
using Sync.Command;
using Sync.MessageFilter;
using Sync.Plugins;
using Sync.Source;
using Sync.Tools;
using System;
using System.Diagnostics;
using static Sync.Tools.IO;
namespace Sync
{
public static class Program
{
//public static I18n i18n;
static void Main(string[] args)
{
/* 程序工作流程:
* 1.程序枚举所有插件,保存所有IPlugin到List中
* 2.程序整理出所有的List<ISourceBase>
* 3.初始化Sync类,Sync类检测配置文件,用正确的类初始化SyncInstance
* 4.程序IO Manager开始工作,等待用户输入
*/
I18n.Instance.ApplyLanguage(new DefaultI18n());
while(true)
{
SyncHost.Instance = new SyncHost();
SyncHost.Instance.Load();
CurrentIO.WriteWelcome();
string cmd = "";
while (true)
{
SyncHost.Instance.Commands.invokeCmdString(cmd);
cmd = CurrentIO.ReadCommand();
}
}
}
}
}
``` |
4c4fccb5-0e40-4384-b121-1e5aaff53724 | {
"language": "C#"
} | ```c#
using Microsoft.VisualStudio.ConnectedServices;
namespace AzureIoTHubConnectedService
{
[ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService",
AppliesTo = "VisualC+WindowsAppContainer")]
internal class CppHandlerWAC : GenericAzureIoTHubServiceHandler
{
protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context)
{
HandlerManifest manifest = new HandlerManifest();
manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8"));
manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1"));
manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.cpp"));
manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.h"));
return manifest;
}
protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context)
{
return new AddServiceInstanceResult(
"",
null
);
}
protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context)
{
return new AzureIoTHubConnectedServiceHandlerHelper(context);
}
}
}
```
Disable UWP C++ (for now) | ```c#
using Microsoft.VisualStudio.ConnectedServices;
namespace AzureIoTHubConnectedService
{
#if false // Disabled to a bug: https://github.com/Azure/azure-iot-sdks/issues/289
[ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService",
AppliesTo = "VisualC+WindowsAppContainer")]
#endif
internal class CppHandlerWAC : GenericAzureIoTHubServiceHandler
{
protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context)
{
HandlerManifest manifest = new HandlerManifest();
manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8"));
manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1"));
manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.cpp"));
manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.h"));
return manifest;
}
protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context)
{
return new AddServiceInstanceResult(
"",
null
);
}
protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context)
{
return new AzureIoTHubConnectedServiceHandlerHelper(context);
}
}
}
``` |
ba6cd961-aff7-46fe-9a36-9aceac39abbd | {
"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 Newtonsoft.Json;
using osu.Game.Online.API;
namespace osu.Game.Online.Multiplayer
{
public class IndexPlaylistScoresRequest : APIRequest<RoomPlaylistScores>
{
private readonly int roomId;
private readonly int playlistItemId;
public IndexPlaylistScoresRequest(int roomId, int playlistItemId)
{
this.roomId = roomId;
this.playlistItemId = playlistItemId;
}
protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores";
}
public class RoomPlaylistScores
{
[JsonProperty("scores")]
public List<MultiplayerScore> Scores { get; set; }
}
}
```
Add additional params to index request | ```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 Newtonsoft.Json;
using osu.Framework.IO.Network;
using osu.Game.Extensions;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
namespace osu.Game.Online.Multiplayer
{
/// <summary>
/// Returns a list of scores for the specified playlist item.
/// </summary>
public class IndexPlaylistScoresRequest : APIRequest<RoomPlaylistScores>
{
private readonly int roomId;
private readonly int playlistItemId;
private readonly Cursor cursor;
private readonly MultiplayerScoresSort? sort;
public IndexPlaylistScoresRequest(int roomId, int playlistItemId, Cursor cursor = null, MultiplayerScoresSort? sort = null)
{
this.roomId = roomId;
this.playlistItemId = playlistItemId;
this.cursor = cursor;
this.sort = sort;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.AddCursor(cursor);
switch (sort)
{
case MultiplayerScoresSort.Ascending:
req.AddParameter("sort", "scores_asc");
break;
case MultiplayerScoresSort.Descending:
req.AddParameter("sort", "scores_desc");
break;
}
return req;
}
protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores";
}
public class RoomPlaylistScores
{
[JsonProperty("scores")]
public List<MultiplayerScore> Scores { get; set; }
}
}
``` |
91d76592-d550-41e7-9d8f-810bb970039e | {
"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;
namespace osu.Game.Rulesets.Difficulty
{
/// <summary>
/// Wraps a <see cref="DifficultyAttributes"/> object and adds a time value for which the attribute is valid.
/// Output by <see cref="DifficultyCalculator.CalculateTimed"/>.
/// </summary>
public class TimedDifficultyAttributes : IComparable<TimedDifficultyAttributes>
{
/// <summary>
/// The non-clock-adjusted time value at which the attributes take effect.
/// </summary>
public readonly double Time;
/// <summary>
/// The attributes.
/// </summary>
public readonly DifficultyAttributes Attributes;
public TimedDifficultyAttributes(double time, DifficultyAttributes attributes)
{
Time = time;
Attributes = attributes;
}
public int CompareTo(TimedDifficultyAttributes other) => Time.CompareTo(other.Time);
}
}
```
Add xmldoc to ctor also | ```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;
namespace osu.Game.Rulesets.Difficulty
{
/// <summary>
/// Wraps a <see cref="DifficultyAttributes"/> object and adds a time value for which the attribute is valid.
/// Output by <see cref="DifficultyCalculator.CalculateTimed"/>.
/// </summary>
public class TimedDifficultyAttributes : IComparable<TimedDifficultyAttributes>
{
/// <summary>
/// The non-clock-adjusted time value at which the attributes take effect.
/// </summary>
public readonly double Time;
/// <summary>
/// The attributes.
/// </summary>
public readonly DifficultyAttributes Attributes;
/// <summary>
/// Creates new <see cref="TimedDifficultyAttributes"/>.
/// </summary>
/// <param name="time">The non-clock-adjusted time value at which the attributes take effect.</param>
/// <param name="attributes">The attributes.</param>
public TimedDifficultyAttributes(double time, DifficultyAttributes attributes)
{
Time = time;
Attributes = attributes;
}
public int CompareTo(TimedDifficultyAttributes other) => Time.CompareTo(other.Time);
}
}
``` |
30d6d6ba-d1e1-44b6-911c-a6ed41ffad3b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace Orchard.Caching {
public class Cache<TKey, TResult> : ICache<TKey, TResult> {
private readonly Dictionary<TKey, CacheEntry> _entries;
public Cache() {
_entries = new Dictionary<TKey, CacheEntry>();
}
public TResult Get(TKey key, Func<AcquireContext<TKey>, TResult> acquire) {
CacheEntry entry;
if (!_entries.TryGetValue(key, out entry) || entry.Tokens.Any(t => !t.IsCurrent)) {
entry = new CacheEntry { Tokens = new List<IVolatileToken>() };
var context = new AcquireContext<TKey>(key, volatileItem => entry.Tokens.Add(volatileItem));
entry.Result = acquire(context);
_entries[key] = entry;
}
return entry.Result;
}
private class CacheEntry {
public TResult Result { get; set; }
public IList<IVolatileToken> Tokens { get; set; }
}
}
}
```
Fix concurrency issue accessing Dictionary instance | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Orchard.Caching {
public class Cache<TKey, TResult> : ICache<TKey, TResult> {
private readonly ConcurrentDictionary<TKey, CacheEntry> _entries;
public Cache() {
_entries = new ConcurrentDictionary<TKey, CacheEntry>();
}
public TResult Get(TKey key, Func<AcquireContext<TKey>, TResult> acquire) {
var entry = _entries.AddOrUpdate(key,
// "Add" lambda
k => CreateEntry(k, acquire),
// "Update" lamdba
(k, currentEntry) => (currentEntry.Tokens.All(t => t.IsCurrent) ? currentEntry : CreateEntry(k, acquire)));
return entry.Result;
}
private static CacheEntry CreateEntry(TKey k, Func<AcquireContext<TKey>, TResult> acquire) {
var entry = new CacheEntry { Tokens = new List<IVolatileToken>() };
var context = new AcquireContext<TKey>(k, volatileItem => entry.Tokens.Add(volatileItem));
entry.Result = acquire(context);
return entry;
}
private class CacheEntry {
public TResult Result { get; set; }
public IList<IVolatileToken> Tokens { get; set; }
}
}
}
``` |
f70d678a-76f2-40f2-9535-265e31632054 | {
"language": "C#"
} | ```c#
using FootballLeague.Models;
using System.DirectoryServices;
namespace FootballLeague.Services
{
public class UsersADSearcher : IUsersADSearcher
{
public User LoadUserDetails(string userName)
{
var entry = new DirectoryEntry();
var searcher = new DirectorySearcher(entry);
searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))";
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("sn");
searcher.PropertiesToLoad.Add("mail");
var userProps = searcher.FindOne().Properties;
var mail = userProps["mail"][0].ToString();
var first = userProps["givenName"][0].ToString();
var last = userProps["sn"][0].ToString();
return new User { Name = userName, Mail = mail, FirstName = first, LastName = last };
}
}
}```
Use local user when not in domain | ```c#
using System.Linq;
using System.Web;
using FootballLeague.Models;
using System.DirectoryServices;
namespace FootballLeague.Services
{
public class UsersADSearcher : IUsersADSearcher
{
public User LoadUserDetails(string userName)
{
var entry = new DirectoryEntry();
var searcher = new DirectorySearcher(entry);
searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))";
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("sn");
searcher.PropertiesToLoad.Add("mail");
try
{
var userProps = searcher.FindOne().Properties;
var mail = userProps["mail"][0].ToString();
var first = userProps["givenName"][0].ToString();
var last = userProps["sn"][0].ToString();
return new User { Name = userName, Mail = mail, FirstName = first, LastName = last };
}
catch
{
return new User { Name = HttpContext.Current.User.Identity.Name.Split('\\').Last(), Mail = "local@user.sk", FirstName = "Local", LastName = "User" };
}
}
}
}``` |
207e22cc-4f11-4f84-a642-94c93c7c08d7 | {
"language": "C#"
} | ```c#
using UnityEditor;
using UnityEditor.Build;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build.Reporting;
#endif
using UnityEngine;
class TeakPreProcessDefiner :
#if UNITY_2018_1_OR_NEWER
IPreprocessBuildWithReport
#else
IPreprocessBuild
#endif
{
public int callbackOrder { get { return 0; } }
public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER" };
#if UNITY_2018_1_OR_NEWER
public void OnPreprocessBuild(BuildReport report) {
SetTeakPreprocesorDefines(report.summary.platformGroup);
}
#else
public void OnPreprocessBuild(BuildTarget target, string path) {
SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target));
}
#endif
private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) {
string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
if (!defines.EndsWith(";")) defines += ";";
defines += string.Join(";", TeakDefines);
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines);
}
}
```
Use a set of defines, and some generics | ```c#
using UnityEditor;
using UnityEditor.Build;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build.Reporting;
#endif
using UnityEngine;
using System.Collections.Generic;
class TeakPreProcessDefiner :
#if UNITY_2018_1_OR_NEWER
IPreprocessBuildWithReport
#else
IPreprocessBuild
#endif
{
public int callbackOrder { get { return 0; } }
public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER" };
#if UNITY_2018_1_OR_NEWER
public void OnPreprocessBuild(BuildReport report) {
SetTeakPreprocesorDefines(report.summary.platformGroup);
}
#else
public void OnPreprocessBuild(BuildTarget target, string path) {
SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target));
}
#endif
private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) {
string[] existingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(";");
HashSet<string> defines = new HashSet<string>(existingDefines);
defines.UnionWith(TeakDefines);
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.ToArray()));
}
}
``` |
cf15b5cb-f777-48ab-b8c8-44849ba132b8 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace Stripe.Tests.Xunit
{
public class coupons_fixture : IDisposable
{
public StripeCouponCreateOptions CouponCreateOptions { get; set; }
public StripeCouponUpdateOptions CouponUpdateOptions { get; set; }
public StripeCoupon Coupon { get; set; }
public StripeCoupon CouponRetrieved { get; set; }
public StripeCoupon CouponUpdated { get; set; }
public StripeDeleted CouponDeleted { get; set; }
public StripeList<StripeCoupon> CouponsList { get; }
public coupons_fixture()
{
CouponCreateOptions = new StripeCouponCreateOptions() {
Id = "test-coupon-" + Guid.NewGuid().ToString() + " ",
PercentOff = 25,
Duration = "repeating",
DurationInMonths = 3,
};
CouponUpdateOptions = new StripeCouponUpdateOptions {
Metadata = new Dictionary<string, string>{{"key_1", "value_1"}}
};
var service = new StripeCouponService(Cache.ApiKey);
Coupon = service.Create(CouponCreateOptions);
CouponRetrieved = service.Get(Coupon.Id);
CouponUpdated = service.Update(Coupon.Id, CouponUpdateOptions);
CouponsList = service.List();
CouponDeleted = service.Delete(Coupon.Id);
}
public void Dispose() { }
}
}
```
Add a detailed comment to explain why we test this | ```c#
using System;
using System.Collections.Generic;
namespace Stripe.Tests.Xunit
{
public class coupons_fixture : IDisposable
{
public StripeCouponCreateOptions CouponCreateOptions { get; set; }
public StripeCouponUpdateOptions CouponUpdateOptions { get; set; }
public StripeCoupon Coupon { get; set; }
public StripeCoupon CouponRetrieved { get; set; }
public StripeCoupon CouponUpdated { get; set; }
public StripeDeleted CouponDeleted { get; set; }
public StripeList<StripeCoupon> CouponsList { get; }
public coupons_fixture()
{
CouponCreateOptions = new StripeCouponCreateOptions() {
// Add a space at the end to ensure the ID is properly URL encoded
// when passed in the URL for other methods
Id = "test-coupon-" + Guid.NewGuid().ToString() + " ",
PercentOff = 25,
Duration = "repeating",
DurationInMonths = 3,
};
CouponUpdateOptions = new StripeCouponUpdateOptions {
Metadata = new Dictionary<string, string>{{"key_1", "value_1"}}
};
var service = new StripeCouponService(Cache.ApiKey);
Coupon = service.Create(CouponCreateOptions);
CouponRetrieved = service.Get(Coupon.Id);
CouponUpdated = service.Update(Coupon.Id, CouponUpdateOptions);
CouponsList = service.List();
CouponDeleted = service.Delete(Coupon.Id);
}
public void Dispose() { }
}
}
``` |
cbeae653-c7f4-440a-acf8-178e4d09dec1 | {
"language": "C#"
} | ```c#
using System.Resources;
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("NesZord.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NesZord.Core")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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")]
```
Enable NesZord.Tests to se internal members of NesZord.Core | ```c#
using System.Resources;
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("NesZord.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NesZord.Core")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("NesZord.Tests")]``` |
ca28e8d8-c2d9-4eb6-afe9-c8359e8ef5ff | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace RazorLight.Extensions
{
public static class TypeExtensions
{
public static ExpandoObject ToExpando(this object anonymousObject)
{
if (anonymousObject is ExpandoObject exp)
{
return exp;
}
IDictionary<string, object> expando = new ExpandoObject();
foreach (var propertyDescriptor in anonymousObject.GetType().GetTypeInfo().GetProperties())
{
var obj = propertyDescriptor.GetValue(anonymousObject);
expando.Add(propertyDescriptor.Name, obj);
}
return (ExpandoObject)expando;
}
public static bool IsAnonymousType(this Type type)
{
bool hasCompilerGeneratedAttribute = type.GetTypeInfo()
.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false)
.Any();
bool nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
bool isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;
return isAnonymousType;
}
}
}
```
Add support for nested anonymous models | ```c#
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace RazorLight.Extensions
{
public static class TypeExtensions
{
public static ExpandoObject ToExpando(this object anonymousObject)
{
if (anonymousObject is ExpandoObject exp)
{
return exp;
}
IDictionary<string, object> expando = new ExpandoObject();
foreach (var propertyDescriptor in anonymousObject.GetType().GetTypeInfo().GetProperties())
{
var obj = propertyDescriptor.GetValue(anonymousObject);
if (obj != null && obj.GetType().IsAnonymousType())
{
obj = obj.ToExpando();
}
expando.Add(propertyDescriptor.Name, obj);
}
return (ExpandoObject)expando;
}
public static bool IsAnonymousType(this Type type)
{
bool hasCompilerGeneratedAttribute = type.GetTypeInfo()
.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false)
.Any();
bool nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
bool isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;
return isAnonymousType;
}
}
}
``` |
b8c2990b-9684-4c9a-8555-add5d66d4c8d | {
"language": "C#"
} | ```c#
using UnityEngine;
namespace PrepareLanding.Core.Extensions
{
public static class FilterBooleanExtensions
{
public static string ToStringHuman(this FilterBoolean filterBool)
{
switch (filterBool)
{
case FilterBoolean.AndFiltering:
return "AND";
case FilterBoolean.OrFiltering:
return "OR";
default:
return "UNK";
}
}
public static FilterBoolean Next(this FilterBoolean filterBoolean)
{
return (FilterBoolean)(((int)filterBoolean + 1) % (int)FilterBoolean.Undefined);
}
public static Color Color(this FilterBoolean filterBoolean)
{
switch (filterBoolean)
{
case FilterBoolean.AndFiltering:
return Verse.ColorLibrary.BurntOrange;
case FilterBoolean.OrFiltering:
return Verse.ColorLibrary.BrightBlue;
default:
return UnityEngine.Color.black;
}
}
}
}```
Allow translation of boolean filtering text. | ```c#
using UnityEngine;
using Verse;
namespace PrepareLanding.Core.Extensions
{
public static class FilterBooleanExtensions
{
public static string ToStringHuman(this FilterBoolean filterBool)
{
switch (filterBool)
{
case FilterBoolean.AndFiltering:
return "PLMWTT_FilterBooleanOr".Translate();
case FilterBoolean.OrFiltering:
return "PLMWTT_FilterBooleanAnd".Translate();
default:
return "UNK";
}
}
public static FilterBoolean Next(this FilterBoolean filterBoolean)
{
return (FilterBoolean)(((int)filterBoolean + 1) % (int)FilterBoolean.Undefined);
}
public static Color Color(this FilterBoolean filterBoolean)
{
switch (filterBoolean)
{
case FilterBoolean.AndFiltering:
return Verse.ColorLibrary.BurntOrange;
case FilterBoolean.OrFiltering:
return Verse.ColorLibrary.BrightBlue;
default:
return UnityEngine.Color.black;
}
}
}
}``` |
0f42069a-ab0d-48b7-83d4-2a1ee65ac070 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.InteropServices;
namespace OpenSage.Utilities
{
public static class PlatformUtility
{
/// <summary>
/// Check if current platform is windows
/// </summary>
/// <returns></returns>
public static bool IsWindowsPlatform()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32Windows:
case PlatformID.Win32NT:
case PlatformID.WinCE:
case PlatformID.Win32S:
return true;
default:
return false;
}
}
public static float GetDefaultDpi()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return 96.0f;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return 72.0f;
}
else
{
return 1.0f; // TODO: What happens on Linux?
}
}
}
}
```
Use correct Gnome3 default DPI | ```c#
using System;
using System.Runtime.InteropServices;
namespace OpenSage.Utilities
{
public static class PlatformUtility
{
/// <summary>
/// Check if current platform is windows
/// </summary>
/// <returns></returns>
public static bool IsWindowsPlatform()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32Windows:
case PlatformID.Win32NT:
case PlatformID.WinCE:
case PlatformID.Win32S:
return true;
default:
return false;
}
}
public static float GetDefaultDpi()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return 96.0f;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return 72.0f;
}
else
{
return 96.0f; // TODO: For GNOME3 the default DPI is 96
}
}
}
}
``` |
55fc8f5a-be54-4259-b0f6-0445b173e76c | {
"language": "C#"
} | ```c#
using System.Text;
using TweetDuck.Plugins.Enums;
namespace TweetDuck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
StringBuilder build = new StringBuilder(2*pluginIdentifier.Length+pluginContents.Length+165);
build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");
build.Append("let tmp={");
build.Append("id:\"").Append(pluginIdentifier).Append("\",");
build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
build.Append("};");
build.Append("tmp.obj.$id=\"").Append(pluginIdentifier).Append("\";");
build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
build.Append("window.TD_PLUGINS.install(tmp);");
build.Append("})(").Append(environment.GetScriptVariables()).Append(");");
return build.ToString();
}
}
}
```
Make $id and $token properties in plugin objects unmodifiable | ```c#
using System.Globalization;
using TweetDuck.Plugins.Enums;
namespace TweetDuck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
return PluginGen
.Replace("%params", environment.GetScriptVariables())
.Replace("%id", pluginIdentifier)
.Replace("%token", pluginToken.ToString(CultureInfo.InvariantCulture))
.Replace("%contents", pluginContents);
}
private const string PluginGen = "(function(%params,$d){let tmp={id:'%id',obj:new class extends PluginBase{%contents}};$d(tmp.obj,'$id',{value:'%id'});$d(tmp.obj,'$token',{value:%token});window.TD_PLUGINS.install(tmp);})(%params,Object.defineProperty);";
/* PluginGen
(function(%params, $i, $d){
let tmp = {
id: '%id',
obj: new class extends PluginBase{%contents}
};
$d(tmp.obj, '$id', { value: '%id' });
$d(tmp.obj, '$token', { value: %token });
window.TD_PLUGINS.install(tmp);
})(%params, Object.defineProperty);
*/
}
}
``` |
4659fc89-0665-415b-8495-1e6f9957430e | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Newtonsoft.Json;
namespace OmniSharp.Models
{
public class Request : SimpleFileRequest
{
[JsonConverter(typeof(ZeroBasedIndexConverter))]
public int Line { get; set; }
[JsonConverter(typeof(ZeroBasedIndexConverter))]
public int Column { get; set; }
public string Buffer { get; set; }
public IEnumerable<LinePositionSpanTextChange> Changes { get; set; }
public bool ApplyChangesTogether { get; set; }
}
}
```
Make ApplyChangesTogether automatically filled to false if not present. | ```c#
using System.Collections.Generic;
using Newtonsoft.Json;
namespace OmniSharp.Models
{
public class Request : SimpleFileRequest
{
[JsonConverter(typeof(ZeroBasedIndexConverter))]
public int Line { get; set; }
[JsonConverter(typeof(ZeroBasedIndexConverter))]
public int Column { get; set; }
public string Buffer { get; set; }
public IEnumerable<LinePositionSpanTextChange> Changes { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool ApplyChangesTogether { get; set; }
}
}
``` |
9161ea54-2cd1-46f0-b92a-36d685eede0d | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace LibYear.Lib.FileTypes
{
public class ProjectJsonFile : IProjectFile
{
private string _fileContents;
public string FileName { get; }
public IDictionary<string, PackageVersion> Packages { get; }
public ProjectJsonFile(string filename)
{
FileName = filename;
_fileContents = File.ReadAllText(FileName);
Packages = GetDependencies().ToDictionary(p => ((JProperty)p).Name.ToString(), p => PackageVersion.Parse(((JProperty)p).Value.ToString()));
}
private IEnumerable<JToken> GetDependencies()
{
return JObject.Parse(_fileContents).Descendants()
.Where(d => d.Type == JTokenType.Property
&& d.Path.Contains("dependencies")
&& (!d.Path.Contains("[") || d.Path.EndsWith("]"))
&& ((JProperty)d).Value.Type == JTokenType.String);
}
public void Update(IEnumerable<Result> results)
{
lock (_fileContents)
{
foreach (var result in results)
_fileContents = _fileContents.Replace($"\"{result.Name}\": \"{result.Installed.Version}\"", $"\"{result.Name}\": \"{result.Latest.Version}\"");
File.WriteAllText(FileName, _fileContents);
}
}
}
}```
Fix JSON file locking issue | ```c#
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace LibYear.Lib.FileTypes
{
public class ProjectJsonFile : IProjectFile
{
private string _fileContents;
public string FileName { get; }
public IDictionary<string, PackageVersion> Packages { get; }
private readonly object _lock = new object();
public ProjectJsonFile(string filename)
{
FileName = filename;
_fileContents = File.ReadAllText(FileName);
Packages = GetDependencies().ToDictionary(p => ((JProperty)p).Name.ToString(), p => PackageVersion.Parse(((JProperty)p).Value.ToString()));
}
private IEnumerable<JToken> GetDependencies()
{
return JObject.Parse(_fileContents).Descendants()
.Where(d => d.Type == JTokenType.Property
&& d.Path.Contains("dependencies")
&& (!d.Path.Contains("[") || d.Path.EndsWith("]"))
&& ((JProperty)d).Value.Type == JTokenType.String);
}
public void Update(IEnumerable<Result> results)
{
lock (_lock)
{
foreach (var result in results)
{
_fileContents = _fileContents.Replace($"\"{result.Name}\": \"{result.Installed.Version}\"", $"\"{result.Name}\": \"{result.Latest.Version}\"");
}
File.WriteAllText(FileName, _fileContents);
}
}
}
}``` |
4a8c3bd3-4d50-4dbc-b7ba-100503123245 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnositySDK.Request;
using LearnositySDK.Utils;
// static LearnositySDK.Credentials;
namespace LearnosityDemo.Pages
{
public class ItemsAPIDemoModel : PageModel
{
public void OnGet()
{
// prepare all the params
string service = "items";
JsonObject security = new JsonObject();
security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey);
security.set("domain", LearnositySDK.Credentials.Domain);
security.set("user_id", Uuid.generate());
string secret = LearnositySDK.Credentials.ConsumerSecret;
//JsonObject config = new JsonObject();
JsonObject request = new JsonObject();
request.set("user_id", Uuid.generate());
request.set("activity_template_id", "quickstart_examples_activity_template_001");
request.set("session_id", Uuid.generate());
request.set("activity_id", "quickstart_examples_activity_001");
request.set("rendering_type", "assess");
request.set("type", "submit_practice");
request.set("name", "Items API Quickstart");
//request.set("config", config);
// Instantiate Init class
Init init = new Init(service, security, secret, request);
// Call the generate() method to retrieve a JavaScript object
ViewData["InitJSON"] = init.generate();
}
}
}
```
Add example for state init option to quick-start guide example project. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnositySDK.Request;
using LearnositySDK.Utils;
// static LearnositySDK.Credentials;
namespace LearnosityDemo.Pages
{
public class ItemsAPIDemoModel : PageModel
{
public void OnGet()
{
// prepare all the params
string service = "items";
JsonObject security = new JsonObject();
security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey);
security.set("domain", LearnositySDK.Credentials.Domain);
security.set("user_id", Uuid.generate());
string secret = LearnositySDK.Credentials.ConsumerSecret;
JsonObject request = new JsonObject();
request.set("user_id", Uuid.generate());
request.set("activity_template_id", "quickstart_examples_activity_template_001");
request.set("session_id", Uuid.generate());
request.set("activity_id", "quickstart_examples_activity_001");
request.set("rendering_type", "assess");
request.set("type", "submit_practice");
request.set("name", "Items API Quickstart");
request.set("state", "initial");
// Instantiate Init class
Init init = new Init(service, security, secret, request);
// Call the generate() method to retrieve a JavaScript object
ViewData["InitJSON"] = init.generate();
}
}
}
``` |
1d2d0d44-f646-4043-8417-14489ca89092 | {
"language": "C#"
} | ```c#
namespace DesktopWidgets.Widgets.RSSFeed
{
public static class Metadata
{
public const string FriendlyName = "RSS Headlines";
}
}```
Change "RSS Headlines" widget name | ```c#
namespace DesktopWidgets.Widgets.RSSFeed
{
public static class Metadata
{
public const string FriendlyName = "RSS Feed";
}
}``` |
2f672a3f-7fb1-43d0-89fe-8082d6460a0b | {
"language": "C#"
} | ```c#
@using Microsoft.ApplicationInsights.Extensibility
@inject TelemetryConfiguration TelemetryConfiguration
<environment names="Production">
<script type="text/javascript">
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' });
ga('mscTracker.send', 'pageview');
</script>
@Html.ApplicationInsightsJavaScript(TelemetryConfiguration)
</environment>
```
Add new Google Analytics tracking ID | ```c#
@using Microsoft.ApplicationInsights.Extensibility
@inject TelemetryConfiguration TelemetryConfiguration
<environment names="Production">
<script type="text/javascript">
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' });
ga('create', 'UA-61337531-4', 'auto', { 'name': 'liveaspnetTracker' });
ga('mscTracker.send', 'pageview');
ga('liveaspnetTracker.send', 'pageview');
</script>
@Html.ApplicationInsightsJavaScript(TelemetryConfiguration)
</environment>
``` |
9e615250-a321-4308-8a0b-d4282560f3e3 | {
"language": "C#"
} | ```c#
using System.Resources;
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("WordPressRestApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevFoundries")]
[assembly: AssemblyProduct("WordPressRestApi")]
[assembly: AssemblyCopyright("Copyright © 2017 Wm. Barrett Simms")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
```
Package rename and add support for Media | ```c#
using System.Resources;
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("WordPressRestApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevFoundries")]
[assembly: AssemblyProduct("WordPressRestApi")]
[assembly: AssemblyCopyright("Copyright © 2017 Wm. Barrett Simms")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
``` |
e37d01c2-f02e-4956-8902-a920b7a7f416 | {
"language": "C#"
} | ```c#
using System;
using QuantConnect.Parameters;
using QuantConnect.Util;
namespace QuantConnect.Data.Custom.Intrinio
{
/// <summary>
/// Auxiliary class to access all Intrinio API data.
/// </summary>
public static class IntrinioConfig
{
/// <summary>
/// </summary>
public static RateGate RateGate =
new RateGate(1, TimeSpan.FromMilliseconds(5000));
/// <summary>
/// Check if Intrinio API user and password are not empty or null.
/// </summary>
public static bool IsInitialized => !string.IsNullOrWhiteSpace(User) && !string.IsNullOrWhiteSpace(Password);
/// <summary>
/// Intrinio API password
/// </summary>
public static string Password = string.Empty;
/// <summary>
/// Intrinio API user
/// </summary>
public static string User = string.Empty;
/// <summary>
/// Set the Intrinio API user and password.
/// </summary>
public static void SetUserAndPassword(string user, string password)
{
User = user;
Password = password;
if (!IsInitialized)
{
throw new InvalidOperationException("Please set a valid Intrinio user and password.");
}
}
}
}```
Increment Intrinio time between calls to 1 minute | ```c#
using System;
using QuantConnect.Parameters;
using QuantConnect.Util;
namespace QuantConnect.Data.Custom.Intrinio
{
/// <summary>
/// Auxiliary class to access all Intrinio API data.
/// </summary>
public static class IntrinioConfig
{
/// <summary>
/// </summary>
public static RateGate RateGate =
new RateGate(1, TimeSpan.FromMinutes(1));
/// <summary>
/// Check if Intrinio API user and password are not empty or null.
/// </summary>
public static bool IsInitialized => !string.IsNullOrWhiteSpace(User) && !string.IsNullOrWhiteSpace(Password);
/// <summary>
/// Intrinio API password
/// </summary>
public static string Password = string.Empty;
/// <summary>
/// Intrinio API user
/// </summary>
public static string User = string.Empty;
/// <summary>
/// Set the Intrinio API user and password.
/// </summary>
public static void SetUserAndPassword(string user, string password)
{
User = user;
Password = password;
if (!IsInitialized)
{
throw new InvalidOperationException("Please set a valid Intrinio user and password.");
}
}
}
}``` |
24e28d02-c119-454d-96a4-36c7cbc1ecf6 | {
"language": "C#"
} | ```c#
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace conekta
{
public class PaymentSource : Resource
{
public string id { get; set; }
public string type { get; set; }
/* In case card token */
public string token_id { get; set; }
/* In case card object*/
public string name { get; set; }
public string number { get; set; }
public string exp_month { get; set; }
public string exp_year { get; set; }
public string cvc { get; set; }
public Address address { get; set; }
public string parent_id { get; set; }
public PaymentSource update(string data)
{
PaymentSource payment_source = this.toClass(this.toObject(this.update("/customers/" + this.parent_id + "/payment_sources/" + this.id, data)).ToString());
return payment_source;
}
public PaymentSource destroy()
{
this.delete("/customers/" + this.parent_id + "/payment_sources/" + this.id);
return this;
}
public PaymentSource toClass(string json)
{
PaymentSource payment_source = JsonConvert.DeserializeObject<PaymentSource>(json, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
return payment_source;
}
}
}
```
Add missing attributes to paymentSource | ```c#
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace conekta
{
public class PaymentSource : Resource
{
public string id { get; set; }
public string type { get; set; }
/* In case card token */
public string token_id { get; set; }
/* In case card object*/
public string name { get; set; }
public string number { get; set; }
public string exp_month { get; set; }
public string exp_year { get; set; }
public string cvc { get; set; }
public string last4 { get; set; }
public string bin { get; set; }
public string brand { get; set; }
public Address address { get; set; }
public string parent_id { get; set; }
public PaymentSource update(string data)
{
PaymentSource payment_source = this.toClass(this.toObject(this.update("/customers/" + this.parent_id + "/payment_sources/" + this.id, data)).ToString());
return payment_source;
}
public PaymentSource destroy()
{
this.delete("/customers/" + this.parent_id + "/payment_sources/" + this.id);
return this;
}
public PaymentSource toClass(string json)
{
PaymentSource payment_source = JsonConvert.DeserializeObject<PaymentSource>(json, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
return payment_source;
}
}
}
``` |
7bd29b80-9dcd-4330-bc99-fbfb594124ad | {
"language": "C#"
} | ```c#
using System.Web.Http;
using System.Web.Routing;
namespace Vidyano.Web2
{
public static class Web2ControllerFactory
{
public static void MapVidyanoWeb2Route(this RouteCollection routes, string routeTemplate = "web2/")
{
routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional });
routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional });
}
}
}```
Handle MapVidyanoWeb2Route for HttpRouteCollection as well | ```c#
using System.Web.Http;
using System.Web.Routing;
namespace Vidyano.Web2
{
public static class Web2ControllerFactory
{
public static void MapVidyanoWeb2Route(this RouteCollection routes, string routeTemplate = "web2/")
{
routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional });
routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional });
}
public static void MapVidyanoWeb2Route(this HttpRouteCollection routes, string routeTemplate = "web2/")
{
routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional });
routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional });
}
}
}``` |
80e100d9-9cd5-449c-839a-e3cc351dc6b3 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.931145117263422, "diffcalc-test")]
[TestCase(1.0736587013228804d, "zero-length-sliders")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new OsuRuleset();
}
}
```
Adjust diffcalc test expected value | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.9311451172608853d, "diffcalc-test")]
[TestCase(1.0736587013228804d, "zero-length-sliders")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new OsuRuleset();
}
}
``` |
622d3460-6035-480c-b2eb-67986eb71052 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Shippo {
[JsonObject (MemberSerialization.OptIn)]
public class Track : ShippoId {
[JsonProperty (PropertyName = "carrier")]
public string Carrier { get; set; }
[JsonProperty (PropertyName = "tracking_number")]
public string TrackingNumber { get; set; }
[JsonProperty (PropertyName = "address_from")]
public ShortAddress AddressFrom { get; set; }
[JsonProperty (PropertyName = "address_to")]
public ShortAddress AddressTo { get; set; }
[JsonProperty (PropertyName = "eta")]
public DateTime? Eta { get; set; }
[JsonProperty (PropertyName = "servicelevel")]
public Servicelevel Servicelevel { get; set; }
[JsonProperty (PropertyName = "tracking_status")]
public TrackingStatus TrackingStatus { get; set; }
[JsonProperty (PropertyName = "tracking_history")]
public List<TrackingHistory> TrackingHistory { get; set; }
[JsonProperty (PropertyName = "metadata")]
public string Metadata { get; set; }
public override string ToString ()
{
return string.Format ("[Track: Carrier={0}, TrackingNumber={1}, AddressFrom={2}, AddressTo={3}, Eta={4}," +
"Servicelevel={5}, TrackingStatus={6}, TrackingHistory={7}, Metadata={8}]",Carrier,
TrackingNumber, AddressFrom, AddressTo, Eta, Servicelevel, TrackingStatus,
TrackingHistory, Metadata);
}
}
}
```
Remove redundant getters and setters | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Shippo {
[JsonObject (MemberSerialization.OptIn)]
public class Track : ShippoId
{
[JsonProperty (PropertyName = "carrier")]
private string Carrier;
[JsonProperty (PropertyName = "tracking_number")]
public string TrackingNumber;
[JsonProperty (PropertyName = "address_from")]
public ShortAddress AddressFrom;
[JsonProperty (PropertyName = "address_to")]
public ShortAddress AddressTo;
[JsonProperty (PropertyName = "eta")]
public DateTime? Eta;
[JsonProperty (PropertyName = "servicelevel")]
public Servicelevel Servicelevel;
[JsonProperty (PropertyName = "tracking_status")]
public TrackingStatus TrackingStatus;
[JsonProperty (PropertyName = "tracking_history")]
public List<TrackingHistory> TrackingHistory;
[JsonProperty (PropertyName = "metadata")]
public string Metadata;
public override string ToString ()
{
return string.Format ("[Track: Carrier={0}, TrackingNumber={1}, AddressFrom={2}, AddressTo={3}, Eta={4}," +
"Servicelevel={5}, TrackingStatus={6}, TrackingHistory={7}, Metadata={8}]",Carrier,
TrackingNumber, AddressFrom, AddressTo, Eta, Servicelevel, TrackingStatus,
TrackingHistory, Metadata);
}
}
}
``` |
48c824f2-b5a0-4579-893e-929262ec5622 | {
"language": "C#"
} | ```c#
namespace OctoAwesome
{
/// <summary>
/// Repräsentiert die physikalischen Eigenschaften eines Blocks/Items/...
/// </summary>
public class PhysicalProperties
{
/// <summary>
/// Härte
/// </summary>
public float Hardness { get; set; }
/// <summary>
/// Dichte in kg/dm^3
/// </summary>
public float Density { get; set; }
/// <summary>
/// Granularität
/// </summary>
public float Granularity { get; set; }
/// <summary>
/// Bruchzähigkeit
/// </summary>
public float FractureToughness { get; set; }
}
}
```
Add comments to physical props | ```c#
namespace OctoAwesome
{
/// <summary>
/// Repräsentiert die physikalischen Eigenschaften eines Blocks/Items/...
/// </summary>
public class PhysicalProperties
{
/// <summary>
/// Härte, welche Materialien können abgebaut werden
/// </summary>
public float Hardness { get; set; }
/// <summary>
/// Dichte in kg/dm^3, Wie viel benötigt (Volumen berechnung) für Crafting bzw. hit result etc....
/// </summary>
public float Density { get; set; }
/// <summary>
/// Granularität, Effiktivität von "Materialien" Schaufel für hohe Werte, Pickaxe für niedrige
/// </summary>
public float Granularity { get; set; }
/// <summary>
/// Bruchzähigkeit, Wie schnell geht etwas zu bruch? Haltbarkeit.
/// </summary>
public float FractureToughness { get; set; }
}
}
``` |
941df08e-4135-46cf-957e-75400cc8853c | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Bindables
{
/// <summary>
/// An interface that represents a read-only leased bindable.
/// </summary>
public interface ILeasedBindable : IBindable
{
/// <summary>
/// End the lease on the source <see cref="Bindable{T}"/>.
/// </summary>
void Return();
}
}
```
Add generic version of interface | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Bindables
{
/// <summary>
/// An interface that represents a read-only leased bindable.
/// </summary>
public interface ILeasedBindable : IBindable
{
/// <summary>
/// End the lease on the source <see cref="Bindable{T}"/>.
/// </summary>
void Return();
}
/// <summary>
/// An interface that representes a read-only leased bindable.
/// </summary>
/// <typeparam name="T">The value type of the bindable.</typeparam>
public interface ILeasedBindable<T> : ILeasedBindable, IBindable<T>
{
}
}
``` |
11899a15-fb22-4e32-8a15-494512717cce | {
"language": "C#"
} | ```c#
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
/// <summary>
/// Provides a set of static methods for querying objects that
/// implement <see cref="IEnumerable{T}" />. The actual methods
/// are implemented in files reflecting the method name.
/// </summary>
public static partial class MoreEnumerable
{
static int? TryGetCollectionCount<T>(this IEnumerable<T> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
return source is ICollection<T> collection ? collection.Count
: source is IReadOnlyCollection<T> readOnlyCollection ? readOnlyCollection.Count
: (int?)null;
}
}
}
```
Remove file structure comment from doc summary | ```c#
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
/// <summary>
/// Provides a set of static methods for querying objects that
/// implement <see cref="IEnumerable{T}" />.
/// </summary>
public static partial class MoreEnumerable
{
static int? TryGetCollectionCount<T>(this IEnumerable<T> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
return source is ICollection<T> collection ? collection.Count
: source is IReadOnlyCollection<T> readOnlyCollection ? readOnlyCollection.Count
: (int?)null;
}
}
}
``` |
fd4b9cea-6a3c-4c6f-9aa8-63bf69ff0240 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Reflection;
namespace TDDUnit {
class Runner {
public Runner(Type exceptType) {
Suite suite = new Suite();
m_result = new Result();
foreach (Type t in Assembly.GetEntryAssembly().GetTypes()) {
if (t.Name.StartsWith("Test") && t.Name != exceptType.Name)
suite.Add(t);
}
foreach (string test in suite.FailedTests(m_result)) {
Console.WriteLine("Failed: " + test);
}
Console.WriteLine(m_result.Summary);
}
public string Summary {
get {
return m_result.Summary;
}
}
private Result m_result;
}
}
```
Add test cases based on inheritance from Case | ```c#
using System;
using System.Linq;
using System.Reflection;
namespace TDDUnit {
class Runner {
public Runner(Type callingType) {
Suite suite = new Suite();
m_result = new Result();
Type[] forbiddenTypes = new Type[] {
callingType
, typeof (TDDUnit.WasRunObj)
, typeof (TDDUnit.WasRunSetUpFailed)
};
foreach (Type t in Assembly.GetEntryAssembly().GetTypes()) {
if (t.IsSubclassOf(typeof (TDDUnit.Case)) && !forbiddenTypes.Contains(t))
suite.Add(t);
}
foreach (string test in suite.FailedTests(m_result)) {
Console.WriteLine("Failed: " + test);
}
Console.WriteLine(m_result.Summary);
}
public string Summary {
get {
return m_result.Summary;
}
}
private Result m_result;
}
}
``` |
7b08de0a-833e-4edb-8423-fde8eb99d6c7 | {
"language": "C#"
} | ```c#
namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class StripeCoupon : StripeEntityWithId, ISupportMetadata
{
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("amount_off")]
public int? AmountOff { get; set; }
[JsonProperty("created")]
[JsonConverter(typeof(StripeDateTimeConverter))]
public DateTime Created { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("duration")]
public string Duration { get; set; }
[JsonProperty("duration_in_months")]
public int? DurationInMonths { get; set; }
[JsonProperty("livemode")]
public bool LiveMode { get; set; }
[JsonProperty("max_redemptions")]
public int? MaxRedemptions { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("percent_off")]
public int? PercentOff { get; set; }
[JsonProperty("redeem_by")]
[JsonConverter(typeof(StripeDateTimeConverter))]
public DateTime? RedeemBy { get; set; }
[JsonProperty("times_redeemed")]
public int TimesRedeemed { get; private set; }
[JsonProperty("valid")]
public bool Valid { get; set; }
}
}
```
Fix the Coupon resource as percent_off is now a decimal | ```c#
namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class StripeCoupon : StripeEntityWithId, ISupportMetadata
{
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("amount_off")]
public int? AmountOff { get; set; }
[JsonProperty("created")]
[JsonConverter(typeof(StripeDateTimeConverter))]
public DateTime Created { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("duration")]
public string Duration { get; set; }
[JsonProperty("duration_in_months")]
public int? DurationInMonths { get; set; }
[JsonProperty("livemode")]
public bool LiveMode { get; set; }
[JsonProperty("max_redemptions")]
public int? MaxRedemptions { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("percent_off")]
public decimal? PercentOff { get; set; }
[JsonProperty("redeem_by")]
[JsonConverter(typeof(StripeDateTimeConverter))]
public DateTime? RedeemBy { get; set; }
[JsonProperty("times_redeemed")]
public int TimesRedeemed { get; private set; }
[JsonProperty("valid")]
public bool Valid { get; set; }
}
}
``` |
01514432-86a5-4ba2-a1bc-6c2ae8ebdb1b | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MitternachtWeb {
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services) {
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if(env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
```
Add the MitternachtBot instance and its services to the ASP.NET services. | ```c#
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using System.Linq;
namespace MitternachtWeb {
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services) {
services.AddControllersWithViews();
services.Add(ServiceDescriptor.Singleton(Program.MitternachtBot));
services.Add(Program.MitternachtBot.Services.Services.Select(s => ServiceDescriptor.Singleton(s.Key, s.Value)));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if(env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
``` |
7d2fdf69-a083-43a9-8727-718b31e6a167 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using CommandLine.Text;
namespace PhotoOrganizer
{
class Program
{
static void Main(string[] args)
{
var opts = new CommandLineOptions();
if (!CommandLine.Parser.Default.ParseArguments(args, opts))
{
Console.WriteLine(HelpText.AutoBuild(opts));
return;
}
if (string.IsNullOrEmpty(opts.SourceFolder))
opts.SourceFolder = System.Environment.CurrentDirectory;
DirectoryInfo destination = new DirectoryInfo(opts.DestinationFolder);
if (!destination.Exists)
{
Console.WriteLine("Error: Destination folder doesn't exist.");
return;
}
DirectoryInfo source = new DirectoryInfo(opts.SourceFolder);
if (!source.Exists)
{
Console.WriteLine("Error: Source folder doesn't exist. Nothing to do.");
return;
}
FileOrganizer organizer = new FileOrganizer(destination, opts);
organizer.ProcessSourceFolder(source);
}
}
}
```
Add warning on delete from source | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using CommandLine.Text;
namespace PhotoOrganizer
{
class Program
{
static void Main(string[] args)
{
var opts = new CommandLineOptions();
if (!CommandLine.Parser.Default.ParseArguments(args, opts))
{
Console.WriteLine(HelpText.AutoBuild(opts));
return;
}
if (string.IsNullOrEmpty(opts.SourceFolder))
opts.SourceFolder = System.Environment.CurrentDirectory;
DirectoryInfo destination = new DirectoryInfo(opts.DestinationFolder);
if (!destination.Exists)
{
Console.WriteLine("Error: Destination folder doesn't exist.");
return;
}
DirectoryInfo source = new DirectoryInfo(opts.SourceFolder);
if (!source.Exists)
{
Console.WriteLine("Error: Source folder doesn't exist. Nothing to do.");
return;
}
if (opts.DeleteSourceOnExistingFile)
{
Console.Write("Delete source files on existing files in destination is enabled.\nTHIS MAY CAUSE DATA LOSS, are you sure? [Y/N]: ");
var key = Console.ReadKey();
if (!(key.KeyChar == 'y' || key.KeyChar == 'Y'))
return;
Console.WriteLine();
}
FileOrganizer organizer = new FileOrganizer(destination, opts);
organizer.ProcessSourceFolder(source);
}
}
}
``` |
a3be3a4c-8205-48e3-b700-83b8c2ec103a | {
"language": "C#"
} | ```c#
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Orchard.Hosting;
using Orchard.Web;
namespace Orchard.Console
{
public class Program
{
public static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(currentDirectory)
.UseWebRoot(currentDirectory)
.UseStartup<Startup>()
.Build();
using (host)
{
host.Start();
var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args);
orchardHost.Run();
}
}
}
}```
Revert "make command line host non blocking" | ```c#
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Orchard.Hosting;
using Orchard.Web;
namespace Orchard.Console
{
public class Program
{
public static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(currentDirectory)
.UseWebRoot(currentDirectory)
.UseStartup<Startup>()
.Build();
using (host)
{
host.Run();
var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args);
orchardHost.Run();
}
}
}
}``` |
77275dfc-e3df-4efc-88d3-f3bd672a8cad | {
"language": "C#"
} | ```c#
using Cafe.Tab;
using Edument.CQRS;
using Events.Cafe;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebFrontend;
namespace CafeTests
{
[TestFixture]
public class AddingEventHandlers
{
[Test]
public void ShouldAddEventHandlers()
{
// Arrange
Guid testId = Guid.NewGuid();
var command = new OpenTab()
{
Id = testId,
TableNumber = 5,
Waiter = "Bob"
};
var expectedEvent = new TabOpened()
{
Id = testId,
TableNumber = 5,
Waiter = "Bob"
};
ISubscribeTo<TabOpened> handler = new EventHandler();
// Act
Domain.Setup();
Domain.Dispatcher.AddSubscriberFor<TabOpened>(handler);
Domain.Dispatcher.SendCommand(command);
// Assert
Assert.AreEqual(expectedEvent.Id, (handler as EventHandler).Actual.Id);
}
public class EventHandler : ISubscribeTo<TabOpened>
{
public TabOpened Actual { get; private set; }
public void Handle(TabOpened e)
{
Actual = e;
}
}
}
}
```
Refactor the arrange part of the test | ```c#
using Cafe.Tab;
using Edument.CQRS;
using Events.Cafe;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebFrontend;
namespace CafeTests
{
[TestFixture]
public class AddingEventHandlers
{
private static void Arrange(out OpenTab command, out TabOpened expectedEvent, out ISubscribeTo<TabOpened> handler)
{
// Arrange
Guid testId = Guid.NewGuid();
command = new OpenTab()
{
Id = testId,
TableNumber = 5,
Waiter = "Bob"
};
expectedEvent = new TabOpened()
{
Id = testId,
TableNumber = 5,
Waiter = "Bob"
};
handler = new EventHandler();
}
[Test]
public void ShouldAddEventHandlers()
{
ISubscribeTo<TabOpened> handler;
OpenTab command;
TabOpened expectedEvent;
Arrange(out command, out expectedEvent, out handler);
// Act
Domain.Setup();
Domain.Dispatcher.AddSubscriberFor<TabOpened>(handler);
Domain.Dispatcher.SendCommand(command);
// Assert
Assert.AreEqual(expectedEvent.Id, (handler as EventHandler).Actual.Id);
}
public class EventHandler : ISubscribeTo<TabOpened>
{
public TabOpened Actual { get; private set; }
public void Handle(TabOpened e)
{
Actual = e;
}
}
}
}
``` |
656d0922-66af-435a-b720-2afba3aa9eb9 | {
"language": "C#"
} | ```c#
using Xunit;
using Squirrel;
using Squirrel.Nodes;
namespace Tests
{
public class EnvironmentTests
{
private static readonly string TestVariableName = "x";
private static readonly INode TestVariableValue = new IntegerNode(1);
[Fact]
public void TestGetValueFromCurrentEnvironment() {
var environment = new Environment();
environment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, environment.Get(TestVariableName));
}
[Fact]
public void TestGetValueFromParentEnvironment() {
var parentEnvironment = new Environment();
var childEnvironment = new Environment(parentEnvironment);
parentEnvironment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
}
[Fact]
public void TestGetValueFromGrandparentEnvironment() {
var grandparentEnvironment = new Environment();
var parentEnvironment = new Environment(grandparentEnvironment);
var childEnvironment = new Environment(parentEnvironment);
grandparentEnvironment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
}
}
}
```
Create negative test for getting values from nested environments | ```c#
using Xunit;
using Squirrel;
using Squirrel.Nodes;
namespace Tests
{
public class EnvironmentTests
{
private static readonly string TestVariableName = "x";
private static readonly INode TestVariableValue = new IntegerNode(1);
[Fact]
public void TestCanGetValueFromCurrentEnvironment() {
var environment = new Environment();
environment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, environment.Get(TestVariableName));
}
[Fact]
public void TestCanGetValueFromParentEnvironment() {
var parentEnvironment = new Environment();
var childEnvironment = new Environment(parentEnvironment);
parentEnvironment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
}
[Fact]
public void TestCanGetValueFromGrandparentEnvironment() {
var grandparentEnvironment = new Environment();
var parentEnvironment = new Environment(grandparentEnvironment);
var childEnvironment = new Environment(parentEnvironment);
grandparentEnvironment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
}
[Fact]
public void TestCannotGetValueFromChildEnvironment() {
var parentEnvironment = new Environment();
var childEnvironment = new Environment(parentEnvironment);
childEnvironment.Put(TestVariableName, TestVariableValue);
Assert.NotEqual(TestVariableValue, parentEnvironment.Get(TestVariableName));
}
}
}
``` |
ce6b99a8-cf4d-4c50-a5d2-5126f8e7ab21 | {
"language": "C#"
} | ```c#
using MongoDB.Bson.Serialization.Attributes;
using System.Diagnostics;
namespace ChessVariantsTraining.Models.Variant960
{
public class Clock
{
Stopwatch stopwatch;
[BsonElement("secondsLeftAfterLatestMove")]
public double SecondsLeftAfterLatestMove
{
get;
set;
}
[BsonElement("increment")]
public int Increment
{
get;
set;
}
public Clock()
{
stopwatch = new Stopwatch();
}
public Clock(TimeControl tc) : this()
{
Increment = tc.Increment;
SecondsLeftAfterLatestMove = tc.InitialSeconds;
}
public void Start()
{
stopwatch.Start();
}
public void Pause()
{
stopwatch.Stop();
stopwatch.Reset();
}
public void AddIncrement()
{
SecondsLeftAfterLatestMove += Increment;
}
public void MoveMade()
{
Pause();
AddIncrement();
SecondsLeftAfterLatestMove = GetSecondsLeft();
}
public double GetSecondsLeft()
{
return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds;
}
}
}
```
Reset stopwatch on Start instead of Pause | ```c#
using MongoDB.Bson.Serialization.Attributes;
using System.Diagnostics;
namespace ChessVariantsTraining.Models.Variant960
{
public class Clock
{
Stopwatch stopwatch;
[BsonElement("secondsLeftAfterLatestMove")]
public double SecondsLeftAfterLatestMove
{
get;
set;
}
[BsonElement("increment")]
public int Increment
{
get;
set;
}
public Clock()
{
stopwatch = new Stopwatch();
}
public Clock(TimeControl tc) : this()
{
Increment = tc.Increment;
SecondsLeftAfterLatestMove = tc.InitialSeconds;
}
public void Start()
{
stopwatch.Reset();
stopwatch.Start();
}
public void Pause()
{
stopwatch.Stop();
}
public void AddIncrement()
{
SecondsLeftAfterLatestMove += Increment;
}
public void MoveMade()
{
Pause();
AddIncrement();
SecondsLeftAfterLatestMove = GetSecondsLeft();
}
public double GetSecondsLeft()
{
return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds;
}
}
}
``` |
c378e85c-8e24-44e5-b67c-003f4bac5d03 | {
"language": "C#"
} | ```c#
using NBi.GenbiL.Action;
using Sprache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.GenbiL.Parser
{
class Action
{
public readonly static Parser<IAction> Parser =
(
from sentence in Case.Parser.Or(Setting.Parser.Or(Suite.Parser.Or(Template.Parser)))
from terminator in Grammar.Terminator.AtLeastOnce()
select sentence
);
}
}
```
Add VariableParser to the main parser | ```c#
using NBi.GenbiL.Action;
using Sprache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.GenbiL.Parser
{
class Action
{
public readonly static Parser<IAction> Parser =
(
from sentence in Case.Parser.Or(Setting.Parser.Or(Suite.Parser.Or(Template.Parser.Or(Variable.Parser))))
from terminator in Grammar.Terminator.AtLeastOnce()
select sentence
);
}
}
``` |
8b7ee74c-e7f5-4683-91a2-6e018c4d2a9b | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Net;
using System.Text;
using Wox.Plugin;
namespace Wox.Infrastructure.Http
{
public class HttpRequest
{
public static string Get(string url, string encoding = "UTF8")
{
return Get(url, encoding, HttpProxy.Instance);
}
private static string Get(string url, string encoding, IHttpProxy proxy)
{
if (string.IsNullOrEmpty(url)) return string.Empty;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Timeout = 10 * 1000;
if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
{
if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port);
}
else
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port)
{
Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
};
}
}
try
{
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{
return reader.ReadToEnd();
}
}
}
}
catch (Exception e)
{
return string.Empty;
}
return string.Empty;
}
}
}```
Fix a http request issues. | ```c#
using System;
using System.IO;
using System.Net;
using System.Text;
using Wox.Plugin;
namespace Wox.Infrastructure.Http
{
public class HttpRequest
{
public static string Get(string url, string encoding = "UTF-8")
{
return Get(url, encoding, HttpProxy.Instance);
}
private static string Get(string url, string encoding, IHttpProxy proxy)
{
if (string.IsNullOrEmpty(url)) return string.Empty;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Timeout = 10 * 1000;
if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
{
if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port);
}
else
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port)
{
Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
};
}
}
try
{
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{
return reader.ReadToEnd();
}
}
}
}
catch (Exception e)
{
return string.Empty;
}
return string.Empty;
}
}
}``` |
95fe27dc-b227-49e5-a872-4f02968c2227 | {
"language": "C#"
} | ```c#
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Batch.SqlServer
{
class BatchRunCommand : IDecorationCommandImplementation
{
private readonly string connectionString;
private readonly string fullPath;
public BatchRunCommand(IBatchRunCommand command, SqlConnection connection)
{
this.connectionString = connection.ConnectionString;
this.fullPath = command.FullPath;
}
public void Execute()
{
if (!File.Exists(fullPath))
throw new ExternalDependencyNotFoundException(fullPath);
var script = File.ReadAllText(fullPath);
var server = new Server();
server.ConnectionContext.ConnectionString = connectionString;
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
```
Add trace to check effective bug | ```c#
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Batch.SqlServer
{
class BatchRunCommand : IDecorationCommandImplementation
{
private readonly string connectionString;
private readonly string fullPath;
public BatchRunCommand(IBatchRunCommand command, SqlConnection connection)
{
this.connectionString = connection.ConnectionString;
this.fullPath = command.FullPath;
}
public void Execute()
{
if (!File.Exists(fullPath))
throw new ExternalDependencyNotFoundException(fullPath);
var script = File.ReadAllText(fullPath);
Trace.WriteLineIf(NBiTraceSwitch.TraceVerbose, script);
var server = new Server();
server.ConnectionContext.ConnectionString = connectionString;
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
``` |
fc9ed815-4851-4fbc-8bc2-ecbbb9af2d87 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Transforms;
using osu.Game.Graphics.Backgrounds;
using osuTK;
namespace osu.Game.Screens
{
public abstract class BlurrableBackgroundScreen : BackgroundScreen
{
protected Background Background;
protected Vector2 BlurTarget;
public TransformSequence<Background> BlurTo(Vector2 sigma, double duration, Easing easing = Easing.None)
=> Background?.BlurTo(BlurTarget = sigma, duration, easing);
}
}
```
Fix songselect blur potentially never being applied | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Transforms;
using osu.Game.Graphics.Backgrounds;
using osuTK;
namespace osu.Game.Screens
{
public abstract class BlurrableBackgroundScreen : BackgroundScreen
{
protected Background Background;
protected Vector2 BlurTarget;
public TransformSequence<Background> BlurTo(Vector2 sigma, double duration, Easing easing = Easing.None)
{
BlurTarget = sigma;
return Background?.BlurTo(BlurTarget, duration, easing);
}
}
}
``` |
df36a8d2-b4e9-4286-8a18-9b8befbc23a7 | {
"language": "C#"
} | ```c#
using System;
using DbLocalizationProvider.Internal;
namespace DbLocalizationProvider.DataAnnotations
{
internal class ModelMetadataLocalizationHelper
{
internal static string GetTranslation(string resourceKey)
{
var result = resourceKey;
if(!ConfigurationContext.Current.EnableLocalization())
{
return result;
}
var localizedDisplayName = LocalizationProvider.Current.GetString(resourceKey);
result = localizedDisplayName;
if(!ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode())
return result;
// for the legacy purposes - we need to look for this resource value as resource translation
// once again - this will make sure that existing XPath resources are still working
if(localizedDisplayName.StartsWith("/"))
{
result = LocalizationProvider.Current.GetString(localizedDisplayName);
}
//If other data annotations exists execept for [Display], an exception is thrown when displayname is ""
//It should be null to avoid exception as ModelMetadata.GetDisplayName only checks for null and not String.Empty
if (string.IsNullOrWhiteSpace(localizedDisplayName))
{
return null;
}
return result;
}
internal static string GetTranslation(Type containerType, string propertyName)
{
var resourceKey = ResourceKeyBuilder.BuildResourceKey(containerType, propertyName);
return GetTranslation(resourceKey);
}
}
}
```
Reformat code in metdata provider | ```c#
using System;
using DbLocalizationProvider.Internal;
namespace DbLocalizationProvider.DataAnnotations
{
internal class ModelMetadataLocalizationHelper
{
internal static string GetTranslation(string resourceKey)
{
var result = resourceKey;
if(!ConfigurationContext.Current.EnableLocalization())
return result;
var localizedDisplayName = LocalizationProvider.Current.GetString(resourceKey);
result = localizedDisplayName;
if(!ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode())
return result;
// for the legacy purposes - we need to look for this resource value as resource translation
// once again - this will make sure that existing XPath resources are still working
if(localizedDisplayName.StartsWith("/"))
result = LocalizationProvider.Current.GetString(localizedDisplayName);
// If other data annotations exists execept for [Display], an exception is thrown when displayname is ""
// It should be null to avoid exception as ModelMetadata.GetDisplayName only checks for null and not String.Empty
return string.IsNullOrWhiteSpace(localizedDisplayName) ? null : result;
}
internal static string GetTranslation(Type containerType, string propertyName)
{
var resourceKey = ResourceKeyBuilder.BuildResourceKey(containerType, propertyName);
return GetTranslation(resourceKey);
}
}
}
``` |
f04caf1d-647f-4d51-87e5-c2317a559e0a | {
"language": "C#"
} | ```c#
using System;
public delegate int IntMap(int x);
public static class Program
{
private static int Apply(IntMap f, int x)
{
return f(x);
}
private static int Square(int x)
{
return x * x;
}
public static void Main()
{
Console.WriteLine(Apply(Square, 10));
}
}```
Make the delegate test more challenging | ```c#
using System;
public delegate T2 Map<T1, T2>(T1 x);
public static class Program
{
private static int Apply(Map<int, int> f, int x)
{
return f(x);
}
private static int Square(int x)
{
return x * x;
}
public static void Main()
{
Console.WriteLine(Apply(Square, 10));
}
}``` |
35604fcc-998a-42b6-b74b-20834eb5985d | {
"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("postalcodefinder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("postalcodefinder")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[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("6a604569-bbd4-4f13-b308-ff3969ff7549")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Update company name and 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("postalcodefinder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Experian")]
[assembly: AssemblyProduct("postalcodefinder")]
[assembly: AssemblyCopyright("Copyright © Experian 2015")]
[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("6a604569-bbd4-4f13-b308-ff3969ff7549")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
``` |
7978a471-18b0-4abe-a557-a4ca389001db | {
"language": "C#"
} | ```c#
namespace LinkedListInOrderInsertion
{
using System;
using System.Collections.Generic;
public class LinkedList
{
private Element Head = null;
private Element Iterator = new Element();
internal void Add(int value)
{
Element insertedElement = new Element { Value = value };
if (Head == null) {
Head = insertedElement;
Iterator.Next = Head;
} else
{
Element current = Head;
if(current.Value > insertedElement.Value) {
Head = insertedElement;
Head.Next = current;
Iterator.Next = Head;
return;
}
while(current.Next != null) {
if(current.Next.Value > insertedElement.Value) {
insertedElement.Next = current.Next;
current.Next = insertedElement;
return;
}
current = current.Next;
}
current.Next = insertedElement;
}
}
internal int Last()
{
Element current = Head;
while (current.Next != null)
{
current = current.Next;
}
return current.Value;
}
internal IEnumerable<Element> Next()
{
if(Iterator.Next != null) {
yield return Iterator.Next;
}
}
}
}
```
Print in reversed order method | ```c#
namespace LinkedListInOrderInsertion
{
using System;
using System.Collections.Generic;
public class LinkedList
{
private Element Head = null;
private Element Iterator = new Element();
internal void Add(int value)
{
Element insertedElement = new Element { Value = value };
if (Head == null) {
Head = insertedElement;
Iterator.Next = Head;
} else
{
Element current = Head;
if(current.Value > insertedElement.Value) {
Head = insertedElement;
Head.Next = current;
Iterator.Next = Head;
return;
}
while(current.Next != null) {
if(current.Next.Value > insertedElement.Value) {
insertedElement.Next = current.Next;
current.Next = insertedElement;
return;
}
current = current.Next;
}
current.Next = insertedElement;
}
}
internal int Last()
{
Element current = Head;
while (current.Next != null)
{
current = current.Next;
}
return current.Value;
}
internal void PrintInReversedOrder(Element startElement) {
if (startElement == null)
{
return;
}
PrintInReversedOrder(startElement.Next);
Console.WriteLine(startElement.Value);
}
internal IEnumerable<Element> Next()
{
if(Iterator.Next != null) {
yield return Iterator.Next;
}
}
}
}
``` |
437b7a6a-f8f0-4f71-b9d5-bec2a80611f3 | {
"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;
namespace osu.Framework.Graphics
{
/// <summary>
/// Holds extension methods for <see cref="Drawable"/>.
/// </summary>
public static class DrawableExtensions
{
/// <summary>
/// Adjusts specified properties of a <see cref="Drawable"/>.
/// </summary>
/// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param>
/// <param name="adjustment">The adjustment function.</param>
/// <returns>The given <see cref="Drawable"/>.</returns>
public static T With<T>(this T drawable, Action<T> adjustment)
where T : Drawable
{
adjustment?.Invoke(drawable);
return drawable;
}
}
}
```
Add extension methods to run guaranteed synchronous disposal | ```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.Development;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Graphics
{
/// <summary>
/// Holds extension methods for <see cref="Drawable"/>.
/// </summary>
public static class DrawableExtensions
{
/// <summary>
/// Adjusts specified properties of a <see cref="Drawable"/>.
/// </summary>
/// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param>
/// <param name="adjustment">The adjustment function.</param>
/// <returns>The given <see cref="Drawable"/>.</returns>
public static T With<T>(this T drawable, Action<T> adjustment)
where T : Drawable
{
adjustment?.Invoke(drawable);
return drawable;
}
/// <summary>
/// Forces removal of this drawable from its parent, followed by immediate synchronous disposal.
/// </summary>
/// <remarks>
/// This is intended as a temporary solution for the fact that there is no way to easily dispose
/// a component in a way that is guaranteed to be synchronously run on the update thread.
///
/// Eventually components will have a better method for unloading.
/// </remarks>
/// <param name="drawable">The <see cref="Drawable"/> to be disposed.</param>
public static void RemoveAndDisposeImmediately(this Drawable drawable)
{
ThreadSafety.EnsureUpdateThread();
switch (drawable.Parent)
{
case Container cont:
cont.Remove(drawable);
break;
case CompositeDrawable comp:
comp.RemoveInternal(drawable);
break;
}
drawable.Dispose();
}
}
}
``` |
f8f8dc91-1f0c-4f56-8ab5-7bc2660746ff | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class Extensions
{
public static DayResult Days(this int days)
{
return new DayResult(days);
}
public static YearResult Years(this int years)
{
return new YearResult(years);
}
public static DateTime Ago(this DayResult result)
{
return DateTime.Now.AddDays(-result.NumberOfDays);
}
public static DateTime Ago(this YearResult result)
{
return DateTime.Now.AddYears(-result.NumberOfYears);
}
public static DateTime FromNow(this DayResult result)
{
return DateTime.Now.AddDays(result.NumberOfDays);
}
public static DateTime FromNow(this YearResult result)
{
return DateTime.Now.AddYears(result.NumberOfYears);
}
}
public class DayResult
{
public DayResult(int numberOfDays)
{
NumberOfDays = numberOfDays;
}
public int NumberOfDays { get; private set; }
}
public class YearResult
{
public YearResult(int numberOfYears)
{
NumberOfYears = numberOfYears;
}
public int NumberOfYears { get; private set; }
}
```
Add support for minutes in date extensions | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class Extensions
{
public static MinuteResult Minutes(this int minutes)
{
return new MinuteResult(minutes);
}
public static DayResult Days(this int days)
{
return new DayResult(days);
}
public static YearResult Years(this int years)
{
return new YearResult(years);
}
public static DateTime Ago(this MinuteResult result)
{
return DateTime.Now.AddMinutes(-result.NumberOfMinutes);
}
public static DateTime Ago(this DayResult result)
{
return DateTime.Now.AddDays(-result.NumberOfDays);
}
public static DateTime Ago(this YearResult result)
{
return DateTime.Now.AddYears(-result.NumberOfYears);
}
public static DateTime FromNow(this DayResult result)
{
return DateTime.Now.AddDays(result.NumberOfDays);
}
public static DateTime FromNow(this YearResult result)
{
return DateTime.Now.AddYears(result.NumberOfYears);
}
}
public class MinuteResult
{
public MinuteResult(int numberOfMinutes)
{
NumberOfMinutes = numberOfMinutes;
}
public int NumberOfMinutes { get; private set; }
}
public class DayResult
{
public DayResult(int numberOfDays)
{
NumberOfDays = numberOfDays;
}
public int NumberOfDays { get; private set; }
}
public class YearResult
{
public YearResult(int numberOfYears)
{
NumberOfYears = numberOfYears;
}
public int NumberOfYears { get; private set; }
}
``` |
5316b869-3330-41ed-b191-f4b1b0a5eee4 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using Newtonsoft.Json;
namespace osu.Game.Users
{
public class UserStatistics
{
[JsonProperty(@"level")]
public LevelInfo Level;
public class LevelInfo
{
[JsonProperty(@"current")]
public int Current;
[JsonProperty(@"progress")]
public int Progress;
}
[JsonProperty(@"pp")]
public decimal? PP;
[JsonProperty(@"pp_rank")]
public int Rank;
[JsonProperty(@"ranked_score")]
public long RankedScore;
[JsonProperty(@"hit_accuracy")]
public decimal Accuracy;
[JsonProperty(@"play_count")]
public int PlayCount;
[JsonProperty(@"total_score")]
public long TotalScore;
[JsonProperty(@"total_hits")]
public int TotalHits;
[JsonProperty(@"maximum_combo")]
public int MaxCombo;
[JsonProperty(@"replays_watched_by_others")]
public int ReplayWatched;
[JsonProperty(@"grade_counts")]
public Grades GradesCount;
public class Grades
{
[JsonProperty(@"ss")]
public int SS;
[JsonProperty(@"s")]
public int S;
[JsonProperty(@"a")]
public int A;
}
}
}
```
Change some small classes to struct to avoid potential null check. | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using Newtonsoft.Json;
namespace osu.Game.Users
{
public class UserStatistics
{
[JsonProperty(@"level")]
public LevelInfo Level;
public struct LevelInfo
{
[JsonProperty(@"current")]
public int Current;
[JsonProperty(@"progress")]
public int Progress;
}
[JsonProperty(@"pp")]
public decimal? PP;
[JsonProperty(@"pp_rank")]
public int Rank;
[JsonProperty(@"ranked_score")]
public long RankedScore;
[JsonProperty(@"hit_accuracy")]
public decimal Accuracy;
[JsonProperty(@"play_count")]
public int PlayCount;
[JsonProperty(@"total_score")]
public long TotalScore;
[JsonProperty(@"total_hits")]
public int TotalHits;
[JsonProperty(@"maximum_combo")]
public int MaxCombo;
[JsonProperty(@"replays_watched_by_others")]
public int ReplayWatched;
[JsonProperty(@"grade_counts")]
public Grades GradesCount;
public struct Grades
{
[JsonProperty(@"ss")]
public int SS;
[JsonProperty(@"s")]
public int S;
[JsonProperty(@"a")]
public int A;
}
}
}
``` |
37005553-268f-4b20-83ab-adbbe5397b81 | {
"language": "C#"
} | ```c#
// WhistTest.cs
// <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright>
using System;
using CardGames.Whist;
namespace ConsoleTesting
{
/// <summary>
/// The whist test class
/// </summary>
public class WhistTest : IGameTest
{
/// <summary>
/// Run the test
/// </summary>
public void RunTest()
{
Whist whist = new Whist();
ConsolePlayer p1 = new ConsolePlayer();
ConsolePlayer p2 = new ConsolePlayer();
ConsolePlayer p3 = new ConsolePlayer();
whist.AddPlayer(p1);
whist.AddPlayer(p2);
whist.AddPlayer(p3);
whist.Start();
}
public void RunWithAi()
{
Console.WriteLine("Es gibt kein AI");
Console.WriteLine("There is no AI")
}
}
}
```
Add english as well as german | ```c#
// WhistTest.cs
// <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright>
using System;
using CardGames.Whist;
namespace ConsoleTesting
{
/// <summary>
/// The whist test class
/// </summary>
public class WhistTest : IGameTest
{
/// <summary>
/// Run the test
/// </summary>
public void RunTest()
{
Whist whist = new Whist();
ConsolePlayer p1 = new ConsolePlayer();
ConsolePlayer p2 = new ConsolePlayer();
ConsolePlayer p3 = new ConsolePlayer();
whist.AddPlayer(p1);
whist.AddPlayer(p2);
whist.AddPlayer(p3);
whist.Start();
}
public void RunWithAi()
{
Console.WriteLine("Es gibt kein AI");
Console.WriteLine("There is no AI");
}
}
}
``` |
9b09350f-113f-4034-b819-fb30e53de0bb | {
"language": "C#"
} | ```c#
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// The following assembly information is common to all Python Tools for Visual
// Studio assemblies.
// If you get compiler errors CS0579, "Duplicate '<attributename>' attribute", check your
// Properties\AssemblyInfo.cs file and remove any lines duplicating the ones below.
// (See also AssemblyVersion.cs in this same directory.)
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Python Tools for Visual Studio")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
```
Update the Copyright year to 2013 | ```c#
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// The following assembly information is common to all Python Tools for Visual
// Studio assemblies.
// If you get compiler errors CS0579, "Duplicate '<attributename>' attribute", check your
// Properties\AssemblyInfo.cs file and remove any lines duplicating the ones below.
// (See also AssemblyVersion.cs in this same directory.)
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Python Tools for Visual Studio")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
``` |
62bac7a3-d372-4bcf-a256-6e4e3cc63f06 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using osu_StreamCompanion.Code.Helpers;
using Sentry;
using StreamCompanionTypes.Enums;
using StreamCompanionTypes.Interfaces.Services;
namespace osu_StreamCompanion.Code.Core.Loggers
{
public class SentryLogger : IContextAwareLogger
{
public static string SentryDsn =
"https://3187b2a91f23411ab7ec5f85ad7d80b8@sentry.pioo.space/2";
public static SentryClient SentryClient { get; } = new SentryClient(new SentryOptions
{
Dsn = SentryDsn,
Release = Program.ScVersion
});
public static Dictionary<string, string> ContextData { get; } = new Dictionary<string, string>();
private object _lockingObject = new object();
public void Log(object logMessage, LogLevel logLevel, params string[] vals)
{
if (logLevel == LogLevel.Critical && logMessage is Exception exception && !(exception is NonLoggableException))
{
var sentryEvent = new SentryEvent(exception);
lock (_lockingObject)
{
foreach (var contextKeyValue in ContextData)
{
sentryEvent.SetExtra(contextKeyValue.Key, contextKeyValue.Value);
}
SentryClient.CaptureEvent(sentryEvent);
}
}
}
public void SetContextData(string key, string value)
{
lock (_lockingObject)
ContextData[key] = value;
}
}
}```
Update sentry to send data necessary for linking events with users | ```c#
using System;
using System.Collections.Generic;
using osu_StreamCompanion.Code.Helpers;
using Sentry;
using StreamCompanionTypes.Enums;
using StreamCompanionTypes.Interfaces.Services;
namespace osu_StreamCompanion.Code.Core.Loggers
{
public class SentryLogger : IContextAwareLogger
{
public static string SentryDsn =
"https://3187b2a91f23411ab7ec5f85ad7d80b8@sentry.pioo.space/2";
public static SentryClient SentryClient { get; } = new SentryClient(new SentryOptions
{
Dsn = SentryDsn,
Release = Program.ScVersion,
SendDefaultPii = true,
BeforeSend = BeforeSend
});
private static SentryEvent? BeforeSend(SentryEvent arg)
{
arg.User.IpAddress = null;
return arg;
}
public static Dictionary<string, string> ContextData { get; } = new Dictionary<string, string>();
private object _lockingObject = new object();
public void Log(object logMessage, LogLevel logLevel, params string[] vals)
{
if (logLevel == LogLevel.Critical && logMessage is Exception exception && !(exception is NonLoggableException))
{
var sentryEvent = new SentryEvent(exception);
lock (_lockingObject)
{
foreach (var contextKeyValue in ContextData)
{
sentryEvent.SetExtra(contextKeyValue.Key, contextKeyValue.Value);
}
SentryClient.CaptureEvent(sentryEvent);
}
}
}
public void SetContextData(string key, string value)
{
lock (_lockingObject)
ContextData[key] = value;
}
}
}``` |
a1366392-fba9-43e4-ab16-f0cdd4abaf8f | {
"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("Slack.Webhooks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Slack.Webhooks")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("98c19dcd-28da-4ebf-8e81-c9e051d65625")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.8.*")]
[assembly: AssemblyFileVersion("0.1.8.0")]
```
Make internals visible to the testing project | ```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("Slack.Webhooks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Slack.Webhooks")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("98c19dcd-28da-4ebf-8e81-c9e051d65625")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.8.*")]
[assembly: AssemblyFileVersion("0.1.8.0")]
[assembly: InternalsVisibleTo("Slack.Webhooks.Tests")]``` |
c33913f7-2ae4-4a6f-89a5-089c59308007 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using SFA.DAS.Audit.Types;
namespace SFA.DAS.EmployerUsers.Domain.Auditing
{
public class AccountLockedAuditMessage : EmployerUsersAuditMessage
{
public AccountLockedAuditMessage(User user)
{
Category = "ACCOUNT_LOCKED";
Description = $"User {user.Email} (id: {user.Id}) has exceeded the limit of failed logins and the account has been locked";
AffectedEntity = new Entity
{
Type = "User",
Id = user.Id
};
ChangedProperties = new List<PropertyUpdate>
{
PropertyUpdate.FromInt(nameof(user.FailedLoginAttempts), user.FailedLoginAttempts)
};
}
}
}
```
Add IsLocked to audit for account locked message | ```c#
using System.Collections.Generic;
using SFA.DAS.Audit.Types;
namespace SFA.DAS.EmployerUsers.Domain.Auditing
{
public class AccountLockedAuditMessage : EmployerUsersAuditMessage
{
public AccountLockedAuditMessage(User user)
{
Category = "ACCOUNT_LOCKED";
Description = $"User {user.Email} (id: {user.Id}) has exceeded the limit of failed logins and the account has been locked";
AffectedEntity = new Entity
{
Type = "User",
Id = user.Id
};
ChangedProperties = new List<PropertyUpdate>
{
PropertyUpdate.FromInt(nameof(user.FailedLoginAttempts), user.FailedLoginAttempts),
PropertyUpdate.FromBool(nameof(user.IsLocked), user.IsLocked)
};
}
}
}
``` |
804c1903-3b45-484f-afb3-8b1d18d0edc3 | {
"language": "C#"
} | ```c#
using System;
using FluentMigrator.Runner.Generators.Generic;
namespace FluentMigrator.Runner.Generators.Jet
{
public class JetQuoter : GenericQuoter
{
public override string OpenQuote { get { return "["; } }
public override string CloseQuote { get { return "]"; } }
public override string CloseQuoteEscapeString { get { return string.Empty; } }
public override string OpenQuoteEscapeString { get { return string.Empty; } }
public override string FormatDateTime(DateTime value)
{
return ValueQuote + (value).ToString("MM/dd/yyyy HH:mm:ss") + ValueQuote;
}
}
}
```
Change date format to iso format | ```c#
using System;
using FluentMigrator.Runner.Generators.Generic;
namespace FluentMigrator.Runner.Generators.Jet
{
public class JetQuoter : GenericQuoter
{
public override string OpenQuote { get { return "["; } }
public override string CloseQuote { get { return "]"; } }
public override string CloseQuoteEscapeString { get { return string.Empty; } }
public override string OpenQuoteEscapeString { get { return string.Empty; } }
public override string FormatDateTime(DateTime value)
{
return ValueQuote + (value).ToString("YYYY-MM-DD HH:mm:ss") + ValueQuote;
}
}
}
``` |
cbd3133d-f343-4a16-be42-667360142c16 | {
"language": "C#"
} | ```c#
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: NotSupportedException
**
**
** Purpose: For methods that should be implemented on subclasses.
**
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.Serialization;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class NotSupportedException : SystemException
{
public NotSupportedException()
: base(Environment.GetResourceString("Arg_NotSupportedException")) {
SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
}
public NotSupportedException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
}
public NotSupportedException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
}
protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
```
Make NotSupportedException partial to allow XI to add an helper method | ```c#
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: NotSupportedException
**
**
** Purpose: For methods that should be implemented on subclasses.
**
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.Serialization;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public partial class NotSupportedException : SystemException
{
public NotSupportedException()
: base(Environment.GetResourceString("Arg_NotSupportedException")) {
SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
}
public NotSupportedException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
}
public NotSupportedException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_NOTSUPPORTED);
}
protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
``` |
51eafde8-28a2-450e-ba69-acb54b13dc40 | {
"language": "C#"
} | ```c#
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SupportManager.DAL;
namespace SupportManager.Web.Infrastructure.ApiKey
{
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
{
private readonly SupportManagerContext db;
public ApiKeyAuthenticationHandler(SupportManagerContext db, IOptionsMonitor<ApiKeyAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
this.db = db;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (Request.Query["apikey"].Count != 1) return AuthenticateResult.Fail("Invalid request");
var key = Request.Query["apikey"][0];
var user = await db.ApiKeys.Where(apiKey => apiKey.Value == key).Select(apiKey => apiKey.User)
.SingleOrDefaultAsync();
if (user == null) return AuthenticateResult.Fail("Invalid API Key");
var claims = new[] {new Claim(ClaimTypes.Name, user.Login)};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
}
```
Support API Key authentication using header | ```c#
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SupportManager.DAL;
namespace SupportManager.Web.Infrastructure.ApiKey
{
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
{
private readonly SupportManagerContext db;
public ApiKeyAuthenticationHandler(SupportManagerContext db, IOptionsMonitor<ApiKeyAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
this.db = db;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string key;
if (Request.Headers["X-API-Key"].Count == 1) key = Request.Headers["X-API-Key"][0];
else if (Request.Query["apikey"].Count == 1) key = Request.Query["apikey"][0];
else return AuthenticateResult.Fail("Invalid request");
var user = await db.ApiKeys.Where(apiKey => apiKey.Value == key).Select(apiKey => apiKey.User)
.SingleOrDefaultAsync();
if (user == null) return AuthenticateResult.Fail("Invalid API Key");
var claims = new[] {new Claim(ClaimTypes.Name, user.Login)};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
}
``` |
513c8e70-abf0-4d7c-a9eb-676352f72701 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using Telegram.Bot.Requests;
using Xunit;
namespace Telegram.Bot.Tests.Unit.Serialization
{
public class MethodNameTests
{
[Fact(DisplayName = "Should serialize method name in webhook responses")]
public void Should_Serialize_MethodName_In_Webhook_Responses()
{
var sendMessageRequest = new SendMessageRequest(1, "text")
{
IsWebhookResponse = true
};
var request = JsonConvert.SerializeObject(sendMessageRequest);
Assert.Contains(@"""method"":""sendMessage""", request);
}
[Fact(DisplayName = "Should not serialize method name in webhook responses")]
public void Should_Not_Serialize_MethodName_In_Webhook_Responses()
{
var sendMessageRequest = new SendMessageRequest(1, "text")
{
IsWebhookResponse = false
};
var request = JsonConvert.SerializeObject(sendMessageRequest);
Assert.DoesNotContain(@"""method"":""sendMessage""", request);
}
}
}
```
Remove var keyword in tests | ```c#
using Newtonsoft.Json;
using Telegram.Bot.Requests;
using Xunit;
namespace Telegram.Bot.Tests.Unit.Serialization
{
public class MethodNameTests
{
[Fact(DisplayName = "Should serialize method name in webhook responses")]
public void Should_Serialize_MethodName_In_Webhook_Responses()
{
SendMessageRequest sendMessageRequest = new SendMessageRequest(1, "text")
{
IsWebhookResponse = true
};
var request = JsonConvert.SerializeObject(sendMessageRequest);
Assert.Contains(@"""method"":""sendMessage""", request);
}
[Fact(DisplayName = "Should not serialize method name in webhook responses")]
public void Should_Not_Serialize_MethodName_In_Webhook_Responses()
{
SendMessageRequest sendMessageRequest = new SendMessageRequest(1, "text")
{
IsWebhookResponse = false
};
var request = JsonConvert.SerializeObject(sendMessageRequest);
Assert.DoesNotContain(@"""method"":""sendMessage""", request);
}
}
}
``` |
302564f2-3a37-4de5-a483-00e437bf0d24 | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
namespace FullSerializer.Internal {
/// <summary>
/// Provides APIs for looking up types based on their name.
/// </summary>
internal static class fsTypeLookup {
public static Type GetType(string typeName) {
//--
// see
// http://answers.unity3d.com/questions/206665/typegettypestring-does-not-work-in-unity.html
// Try Type.GetType() first. This will work with types defined by the Mono runtime, in
// the same assembly as the caller, etc.
var type = Type.GetType(typeName);
// If it worked, then we're done here
if (type != null)
return type;
// If the TypeName is a full name, then we can try loading the defining assembly
// directly
if (typeName.Contains(".")) {
// Get the name of the assembly (Assumption is that we are using fully-qualified
// type names)
var assemblyName = typeName.Substring(0, typeName.IndexOf('.'));
// Attempt to load the indicated Assembly
var assembly = Assembly.Load(assemblyName);
if (assembly == null)
return null;
// Ask that assembly to return the proper Type
type = assembly.GetType(typeName);
if (type != null)
return type;
}
// If we still haven't found the proper type, we can enumerate all of the loaded
// assemblies and see if any of them define the type
var currentAssembly = Assembly.GetExecutingAssembly();
var referencedAssemblies = currentAssembly.GetReferencedAssemblies();
foreach (var assemblyName in referencedAssemblies) {
// Load the referenced assembly
var assembly = Assembly.Load(assemblyName);
if (assembly != null) {
// See if that assembly defines the named type
type = assembly.GetType(typeName);
if (type != null)
return type;
}
}
// The type just couldn't be found...
return null;
}
}
}```
Fix buggy type lookup when Type.FindType fails | ```c#
using System;
using System.Reflection;
namespace FullSerializer.Internal {
/// <summary>
/// Provides APIs for looking up types based on their name.
/// </summary>
internal static class fsTypeLookup {
/// <summary>
/// Attempts to lookup the given type. Returns null if the type lookup fails.
/// </summary>
public static Type GetType(string typeName) {
Type type = null;
// Try a direct type lookup
type = Type.GetType(typeName);
if (type != null) {
return type;
}
// If we still haven't found the proper type, we can enumerate all of the loaded
// assemblies and see if any of them define the type
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
// See if that assembly defines the named type
type = assembly.GetType(typeName);
if (type != null) {
return type;
}
}
return null;
}
}
}``` |
add252df-2c3c-481c-a026-7a91f4bd48f3 | {
"language": "C#"
} | ```c#
using Lokad.Cqrs.Build.Engine;
using NUnit.Framework;
namespace Lokad.Cqrs
{
[TestFixture]
public sealed class MiscTests
{
// ReSharper disable InconsistentNaming
[Test]
public void Azure_queues_regex_is_valid()
{
Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("some-queue"));
Assert.IsFalse(AzureEngineModule.QueueName.IsMatch("-some-queue"));
}
}
}```
Verify that "to-project" is a valid queue name | ```c#
using Lokad.Cqrs.Build.Engine;
using NUnit.Framework;
namespace Lokad.Cqrs
{
[TestFixture]
public sealed class MiscTests
{
// ReSharper disable InconsistentNaming
[Test]
public void Azure_queues_regex_is_valid()
{
Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("some-queue"));
Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("to-watchtower"));
Assert.IsFalse(AzureEngineModule.QueueName.IsMatch("-some-queue"));
}
}
}``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.