doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
64f90b89-2703-4568-9eee-79b472567269 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace Verdeler
{
public class Distributor<TDistributable> : IDistributor<TDistributable> where TDistributable : IDistributable
{
private readonly List<IEndpointRepository> _endpointRepositories
= new List<IEndpointRepository>();
private readonly Dictionary<Type, IEndpointDeliveryService> _endpointDeliveryServices
= new Dictionary<Type, IEndpointDeliveryService>();
public void RegisterEndpointRepository(IEndpointRepository endpointRepository)
{
if (!_endpointRepositories.Contains(endpointRepository))
{
_endpointRepositories.Add(endpointRepository);
}
}
public void RegisterEndpointDeliveryService<TEndpoint>(IEndpointDeliveryService<TEndpoint> endpointDeliveryService)
{
_endpointDeliveryServices[typeof(TEndpoint)] = endpointDeliveryService;
}
public void Distribute(TDistributable distributable, string recipientName)
{
var endpoints = _endpointRepositories.SelectMany(r => r.GetEndpointsForRecipient(recipientName));
foreach (var endpoint in endpoints)
{
var endpointDeliveryService = _endpointDeliveryServices[endpoint.GetType()];
endpointDeliveryService.Deliver(distributable, endpoint);
}
}
}
}
```
Add IEndpoint restriction to RegisterEndpointDeliveryService. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace Verdeler
{
public class Distributor<TDistributable> : IDistributor<TDistributable> where TDistributable : IDistributable
{
private readonly List<IEndpointRepository> _endpointRepositories
= new List<IEndpointRepository>();
private readonly Dictionary<Type, IEndpointDeliveryService> _endpointDeliveryServices
= new Dictionary<Type, IEndpointDeliveryService>();
public void RegisterEndpointRepository(IEndpointRepository endpointRepository)
{
if (!_endpointRepositories.Contains(endpointRepository))
{
_endpointRepositories.Add(endpointRepository);
}
}
public void RegisterEndpointDeliveryService<TEndpoint>(IEndpointDeliveryService<TEndpoint> endpointDeliveryService)
where TEndpoint : IEndpoint
{
_endpointDeliveryServices[typeof(TEndpoint)] = endpointDeliveryService;
}
public void Distribute(TDistributable distributable, string recipientName)
{
var endpoints = _endpointRepositories.SelectMany(r => r.GetEndpointsForRecipient(recipientName));
foreach (var endpoint in endpoints)
{
var endpointDeliveryService = _endpointDeliveryServices[endpoint.GetType()];
endpointDeliveryService.Deliver(distributable, endpoint);
}
}
}
}
``` |
eee9a5bb-0ce7-4ee9-aa71-0653d032ca4f | {
"language": "C#"
} | ```c#
using NetSh;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WifiProfiles
{
class Program
{
static void Main(string[] args)
{
var profiles = NetShWrapper.GetWifiProfiles();
bool sawBadWifi = false;
foreach (var a in profiles)
{
string warning = NetShWrapper.IsOpenAndAutoWifiProfile(a) ? "Warning: AUTO connect to OPEN WiFi" : String.Empty;
Console.WriteLine(String.Format("{0,-20} {1,10} {2,10} {3,30} ", a.Name, a.ConnectionMode, a.Authentication, warning));
if (!String.IsNullOrWhiteSpace(warning)) sawBadWifi = true;
}
if (sawBadWifi)
{
Console.WriteLine("\r\nDelete WiFi profiles that are OPEN *and* AUTO connect? [y/n]");
if (args[0].ToUpperInvariant() == "/DELETEAUTOOPEN" || Console.ReadLine().Trim().ToUpperInvariant()[0] == 'Y')
{
Console.WriteLine("in here");
foreach (var a in profiles.Where(a => NetShWrapper.IsOpenAndAutoWifiProfile(a)))
{
Console.WriteLine(NetShWrapper.DeleteWifiProfile(a));
}
}
}
else
{
Console.WriteLine("\r\nNo WiFi profiles set to OPEN and AUTO connect were found. \r\nOption: Run with /deleteautoopen to auto delete.");
}
//Console.ReadKey();
}
}
}
```
Fix crashes when no arguments or no input | ```c#
using NetSh;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WifiProfiles
{
class Program
{
static void Main(string[] args)
{
var profiles = NetShWrapper.GetWifiProfiles();
bool sawBadWifi = false;
foreach (var a in profiles)
{
string warning = NetShWrapper.IsOpenAndAutoWifiProfile(a) ? "Warning: AUTO connect to OPEN WiFi" : String.Empty;
Console.WriteLine(String.Format("{0,-20} {1,10} {2,10} {3,30} ", a.Name, a.ConnectionMode, a.Authentication, warning));
if (!String.IsNullOrWhiteSpace(warning)) sawBadWifi = true;
}
if (sawBadWifi)
{
Console.WriteLine("\r\nDelete WiFi profiles that are OPEN *and* AUTO connect? [y/n]");
if (args.Length > 0 && args[0].ToUpperInvariant() == "/DELETEAUTOOPEN" ||
Console.ReadLine().Trim().ToUpperInvariant().StartsWith("Y"))
{
Console.WriteLine("in here");
foreach (var a in profiles.Where(a => NetShWrapper.IsOpenAndAutoWifiProfile(a)))
{
Console.WriteLine(NetShWrapper.DeleteWifiProfile(a));
}
}
}
else
{
Console.WriteLine("\r\nNo WiFi profiles set to OPEN and AUTO connect were found. \r\nOption: Run with /deleteautoopen to auto delete.");
}
//Console.ReadKey();
}
}
}
``` |
ef4df0d2-2632-40c3-8016-2d1706394208 | {
"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("ElitePlayerJournal")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ElitePlayerJournal")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("195b246a-62a6-4399-944a-4ad55e722994")]
// 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("Netwonsoft.Json")]
```
Add copyright info in DLL properties. | ```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("ElitePlayerJournal")]
[assembly: AssemblyDescription("A library for reading Elite Dangerous player journal files.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ElitePlayerJournal")]
[assembly: AssemblyCopyright("Copyright © Jamie Anderson 2017")]
[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("195b246a-62a6-4399-944a-4ad55e722994")]
// 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")]
``` |
12db5b29-ba73-44fe-83cb-3ffda7594a1e | {
"language": "C#"
} | ```c#
using System.Web.Http;
using Bit.WebApi.ActionFilters;
using Bit.WebApi.Contracts;
namespace Bit.WebApi.Implementations
{
public class GlobalHostAuthenticationFilterProvider : IWebApiConfigurationCustomizer
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));
}
}
public class GlobalDefaultExceptionHandlerActionFilterProvider<TExceptionHandlerFilterAttribute> : IWebApiConfigurationCustomizer
where TExceptionHandlerFilterAttribute : ExceptionHandlerFilterAttribute, new()
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new TExceptionHandlerFilterAttribute());
}
}
public class GlobalDefaultLogOperationArgsActionFilterProvider<TOperationArgsArgs> : IWebApiConfigurationCustomizer
where TOperationArgsArgs : LogOperationArgsFilterAttribute, new()
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new TOperationArgsArgs());
}
}
public class GlobalDefaultRequestModelStateValidatorActionFilterProvider : IWebApiConfigurationCustomizer
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new RequestModelStateValidatorActionFilterAttribute());
}
}
}
```
Support for basic auth in web api & odata | ```c#
using System.Web.Http;
using Bit.WebApi.ActionFilters;
using Bit.WebApi.Contracts;
namespace Bit.WebApi.Implementations
{
public class GlobalHostAuthenticationFilterProvider : IWebApiConfigurationCustomizer
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));
webApiConfiguration.Filters.Add(new HostAuthenticationFilter("Basic"));
}
}
public class GlobalDefaultExceptionHandlerActionFilterProvider<TExceptionHandlerFilterAttribute> : IWebApiConfigurationCustomizer
where TExceptionHandlerFilterAttribute : ExceptionHandlerFilterAttribute, new()
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new TExceptionHandlerFilterAttribute());
}
}
public class GlobalDefaultLogOperationArgsActionFilterProvider<TOperationArgsArgs> : IWebApiConfigurationCustomizer
where TOperationArgsArgs : LogOperationArgsFilterAttribute, new()
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new TOperationArgsArgs());
}
}
public class GlobalDefaultRequestModelStateValidatorActionFilterProvider : IWebApiConfigurationCustomizer
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new RequestModelStateValidatorActionFilterAttribute());
}
}
}
``` |
223f390b-19fb-45aa-837d-fcc60084e902 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using ApprovalTests;
using ApprovalTests.Reporters;
using FluentAssertions;
using Xunit;
using Grobid.NET;
using org.apache.log4j;
using org.grobid.core;
namespace Grobid.Test
{
[UseReporter(typeof(DiffReporter))]
public class GrobidTest
{
static GrobidTest()
{
BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(Level.INFO);
}
[Fact]
[Trait("Test", "EndToEnd")]
public void ExtractTest()
{
var binPath = Environment.GetEnvironmentVariable("PDFTOXMLEXE");
var factory = new GrobidFactory(
"grobid.zip",
binPath,
Directory.GetCurrentDirectory());
var grobid = factory.Create();
var result = grobid.Extract(@"essence-linq.pdf");
result.Should().NotBeEmpty();
Approvals.Verify(result);
}
[Fact]
public void Test()
{
var x = GrobidModels.NAMES_HEADER;
x.name().Should().Be("NAMES_HEADER");
x.toString().Should().Be("name/header");
}
}
}
```
Set log level to DEBUG | ```c#
using System;
using System.IO;
using ApprovalTests;
using ApprovalTests.Reporters;
using FluentAssertions;
using Xunit;
using Grobid.NET;
using org.apache.log4j;
using org.grobid.core;
namespace Grobid.Test
{
[UseReporter(typeof(DiffReporter))]
public class GrobidTest
{
static GrobidTest()
{
BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG);
}
[Fact]
[Trait("Test", "EndToEnd")]
public void ExtractTest()
{
var binPath = Environment.GetEnvironmentVariable("PDFTOXMLEXE");
org.apache.log4j.Logger.getRootLogger().info("PDFTOXMLEXE=" + binPath);
var factory = new GrobidFactory(
"grobid.zip",
binPath,
Directory.GetCurrentDirectory());
var grobid = factory.Create();
var result = grobid.Extract(@"essence-linq.pdf");
result.Should().NotBeEmpty();
Approvals.Verify(result);
}
[Fact]
public void Test()
{
var x = GrobidModels.NAMES_HEADER;
x.name().Should().Be("NAMES_HEADER");
x.toString().Should().Be("name/header");
}
}
}
``` |
bb792339-b409-4e37-bddf-d4c3a04d9d7e | {
"language": "C#"
} | ```c#
using Microsoft.Win32;
using System.IO;
namespace StorybrewEditor.Util
{
public static class OsuHelper
{
public static string GetOsuPath()
{
using (var registryKey = Registry.ClassesRoot.OpenSubKey("osu\\DefaultIcon"))
{
if (registryKey == null)
return string.Empty;
var value = registryKey.GetValue(null).ToString();
var startIndex = value.IndexOf("\"");
var endIndex = value.LastIndexOf("\"");
return value.Substring(startIndex + 1, endIndex - 1);
}
}
public static string GetOsuFolder()
=> Path.GetDirectoryName(GetOsuPath());
public static string GetOsuSongFolder()
{
var osuFolder = Path.GetDirectoryName(GetOsuPath());
var songsFolder = Path.Combine(osuFolder, "Songs");
return Directory.Exists(songsFolder) ? songsFolder : osuFolder;
}
}
}
```
Fix crash when creating a new project if osu!'s folder could not be found. | ```c#
using Microsoft.Win32;
using System;
using System.IO;
namespace StorybrewEditor.Util
{
public static class OsuHelper
{
public static string GetOsuPath()
{
using (var registryKey = Registry.ClassesRoot.OpenSubKey("osu\\DefaultIcon"))
{
if (registryKey == null)
return string.Empty;
var value = registryKey.GetValue(null).ToString();
var startIndex = value.IndexOf("\"");
var endIndex = value.LastIndexOf("\"");
return value.Substring(startIndex + 1, endIndex - 1);
}
}
public static string GetOsuFolder()
{
var osuPath = GetOsuPath();
if (osuPath.Length == 0)
return Path.GetPathRoot(Environment.SystemDirectory);
return Path.GetDirectoryName(osuPath);
}
public static string GetOsuSongFolder()
{
var osuPath = GetOsuPath();
if (osuPath.Length == 0)
return Path.GetPathRoot(Environment.SystemDirectory);
var osuFolder = Path.GetDirectoryName(osuPath);
var songsFolder = Path.Combine(osuFolder, "Songs");
return Directory.Exists(songsFolder) ? songsFolder : osuFolder;
}
}
}
``` |
4af72cf9-ed0b-4229-ad2a-a51271c2bdf7 | {
"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("Pather.CSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pather.CSharp")]
[assembly: AssemblyCopyright("Copyright © 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("0ce3a750-ffd7-49d1-a737-204ec60c70a5")]
```
Add version information and description to the assembly | ```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("Pather.CSharp")]
[assembly: AssemblyDescription("Pather.CSharp - A Path Resolution Library for C#")]
[assembly: AssemblyVersion("0.1")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pather.CSharp")]
[assembly: AssemblyCopyright("Copyright © 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("0ce3a750-ffd7-49d1-a737-204ec60c70a5")]
``` |
23e47a5a-6969-4f43-812b-df4723bf04f7 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class RandomColor : MonoBehaviour {
void Start () {
// var c = new Color(Random.value, Random.value, Random.value, 1f);
var c = new Color(0, 0, 1f, 1f);
GetComponent<Renderer>().material.color = c;
}
}
```
Change color to read to test sub-module. | ```c#
using UnityEngine;
using System.Collections;
public class RandomColor : MonoBehaviour {
void Start () {
// var c = new Color(Random.value, Random.value, Random.value, 1f);
var c = new Color(1f, 0, 0f, 1f);
GetComponent<Renderer>().material.color = c;
}
}
``` |
6657fc77-1908-474b-b4fe-9e4eb3c1f154 | {
"language": "C#"
} | ```c#
using Glimpse.Agent;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Glimpse.Server.Web;
using Glimpse.Web;
using Microsoft.Extensions.OptionsModel;
namespace Glimpse
{
public class GlimpseServerWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Common
//
services.AddSingleton<IServerBroker, DefaultServerBroker>();
services.AddSingleton<IStorage, InMemoryStorage>();
services.AddSingleton<IScriptOptionsProvider, DefaultScriptOptionsProvider>();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseServerWebOptions>, GlimpseServerWebOptionsSetup>();
services.AddTransient<IExtensionProvider<IAllowClientAccess>, DefaultExtensionProvider<IAllowClientAccess>>();
services.AddTransient<IExtensionProvider<IAllowAgentAccess>, DefaultExtensionProvider<IAllowAgentAccess>>();
services.AddTransient<IExtensionProvider<IResource>, DefaultExtensionProvider<IResource>>();
services.AddTransient<IExtensionProvider<IResourceStartup>, DefaultExtensionProvider<IResourceStartup>>();
services.AddSingleton<IAllowRemoteProvider, DefaultAllowRemoteProvider>();
services.AddTransient<IResourceManager, ResourceManager>();
return services;
}
public static IServiceCollection GetLocalAgentServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IMessagePublisher, InProcessChannel>();
return services;
}
}
}```
Make sure required services are registered | ```c#
using Glimpse.Agent;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Glimpse.Server.Web;
using Glimpse.Web;
using Microsoft.Extensions.OptionsModel;
namespace Glimpse
{
public class GlimpseServerWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Common
//
services.AddSingleton<IServerBroker, DefaultServerBroker>();
services.AddSingleton<IStorage, InMemoryStorage>();
services.AddTransient<IResourceManager, ResourceManager>();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseServerWebOptions>, GlimpseServerWebOptionsSetup>();
services.AddTransient<IExtensionProvider<IAllowClientAccess>, DefaultExtensionProvider<IAllowClientAccess>>();
services.AddTransient<IExtensionProvider<IAllowAgentAccess>, DefaultExtensionProvider<IAllowAgentAccess>>();
services.AddTransient<IExtensionProvider<IResource>, DefaultExtensionProvider<IResource>>();
services.AddTransient<IExtensionProvider<IResourceStartup>, DefaultExtensionProvider<IResourceStartup>>();
services.AddSingleton<IAllowRemoteProvider, DefaultAllowRemoteProvider>();
services.AddSingleton<IScriptOptionsProvider, DefaultScriptOptionsProvider>();
services.AddSingleton<IMetadataProvider, DefaultMetadataProvider>();
return services;
}
public static IServiceCollection GetLocalAgentServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IMessagePublisher, InProcessChannel>();
return services;
}
}
}``` |
75f61950-d543-4f6a-8062-78d7fed81bb5 | {
"language": "C#"
} | ```c#
@model BlogSystem.Web.ViewModels.Comment.CommentViewModel
<h3>Leave a Comment</h3>
@if (User.Identity.IsAuthenticated)
{
using (Ajax.BeginForm("Create", "Comments", new { id = ViewData["id"].ToString() }, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "comments", OnFailure = "BlogSystem.onCreateCommentFailure" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, string.Empty, new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control " } })
@Html.ValidationMessageFor(model => model.Content, string.Empty, new { @class = "text-danger" })
</div>
<button type="submit" class="btn btn-default">Add Comment</button>
}
}
else
{
<p>Only registered users can comment.</p>
}```
Update Create Comment Ajax Form | ```c#
@model BlogSystem.Web.ViewModels.Comment.CommentViewModel
<h3>Leave a Comment</h3>
@if (User.Identity.IsAuthenticated)
{
using (Ajax.BeginForm("Create", "Comments", new { id = ViewData["id"].ToString() }, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "comments", OnFailure = "BlogSystem.onCreateCommentFailure", OnSuccess = "BlogSystem.onAddCommentSuccess" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, string.Empty, new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control " } })
@Html.ValidationMessageFor(model => model.Content, string.Empty, new { @class = "text-danger" })
</div>
<button type="submit" class="btn btn-default">Add Comment</button>
}
}
else
{
<p>Only registered users can comment.</p>
}``` |
c81982cc-ce0a-47fb-9672-cb74e7a39c34 | {
"language": "C#"
} | ```c#
using System;
using System.Text;
using Titanium.Web.Proxy.Http;
using Titanium.Web.Proxy.Shared;
namespace Titanium.Web.Proxy.Extensions
{
internal static class HttpWebResponseExtensions
{
/// <summary>
/// Gets the character encoding of response from response headers
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
internal static Encoding GetResponseCharacterEncoding(this Response response)
{
try
{
//return default if not specified
if (response.ContentType == null)
{
return Encoding.GetEncoding("ISO-8859-1");
}
//extract the encoding by finding the charset
var contentTypes = response.ContentType.Split(ProxyConstants.SemiColonSplit);
foreach (var contentType in contentTypes)
{
var encodingSplit = contentType.Split(ProxyConstants.EqualSplit, 2);
if (encodingSplit.Length == 2 && encodingSplit[0].Trim().Equals("charset", StringComparison.CurrentCultureIgnoreCase))
{
string value = encodingSplit[1];
if (value.Equals("x-user-defined", StringComparison.OrdinalIgnoreCase))
{
//todo: what is this?
continue;
}
if (value[0] == '"' && value[value.Length - 1] == '"')
{
value = value.Substring(1, value.Length - 2);
}
return Encoding.GetEncoding(value);
}
}
}
catch
{
//parsing errors
// ignored
}
//return default if not specified
return Encoding.GetEncoding("ISO-8859-1");
}
}
}
```
Check the value length to avoid exceptions. | ```c#
using System;
using System.Text;
using Titanium.Web.Proxy.Http;
using Titanium.Web.Proxy.Shared;
namespace Titanium.Web.Proxy.Extensions
{
internal static class HttpWebResponseExtensions
{
/// <summary>
/// Gets the character encoding of response from response headers
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
internal static Encoding GetResponseCharacterEncoding(this Response response)
{
try
{
//return default if not specified
if (response.ContentType == null)
{
return Encoding.GetEncoding("ISO-8859-1");
}
//extract the encoding by finding the charset
var contentTypes = response.ContentType.Split(ProxyConstants.SemiColonSplit);
foreach (var contentType in contentTypes)
{
var encodingSplit = contentType.Split(ProxyConstants.EqualSplit, 2);
if (encodingSplit.Length == 2 && encodingSplit[0].Trim().Equals("charset", StringComparison.CurrentCultureIgnoreCase))
{
string value = encodingSplit[1];
if (value.Equals("x-user-defined", StringComparison.OrdinalIgnoreCase))
{
//todo: what is this?
continue;
}
if (value.Length > 2 && value[0] == '"' && value[value.Length - 1] == '"')
{
value = value.Substring(1, value.Length - 2);
}
return Encoding.GetEncoding(value);
}
}
}
catch
{
//parsing errors
// ignored
}
//return default if not specified
return Encoding.GetEncoding("ISO-8859-1");
}
}
}
``` |
ba5553c3-5c6a-4725-81f9-e8b37302d7ad | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chain
{
public interface IChain
{
IList<ILink> Links { get; }
void ConnectAllLinks();
void LoopLinks(int amountOfLoops);
void RunLinks();
}
public class Chain : IChain
{
private IList<ILink> _Links;
public Chain()
{
}
public IList<ILink> Links
{
get { throw new NotImplementedException(); }
}
public void ConnectAllLinks()
{
throw new NotImplementedException();
}
public void LoopLinks(int amountOfLoops)
{
int i = 0;
while (i < amountOfLoops)
{
i++;
RunLinks();
}
}
public void RunLinks()
{
foreach (ILink link in _Links)
{
if(link.IsEnabled)
{
link.HookBeforeLink();
link.RunLink();
link.HookAfterLink();
}
}
}
}
}
```
Implement link property and added add link method | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chain
{
public interface IChain
{
IList<ILink> Links { get; }
void ConnectAllLinks();
void LoopLinks(int amountOfLoops);
void RunLinks();
void AddLink(ILink link);
}
public class Chain : IChain
{
private IList<ILink> _Links;
public Chain()
{
_Links = new List<ILink>();
}
public IList<ILink> Links
{
get { return _Links; }
}
public void ConnectAllLinks()
{
throw new NotImplementedException();
}
public void LoopLinks(int amountOfLoops)
{
int i = 0;
while (i < amountOfLoops)
{
i++;
RunLinks();
}
}
public void RunLinks()
{
foreach (ILink link in _Links)
{
if(link.IsEnabled)
{
link.HookBeforeLink();
link.RunLink();
link.HookAfterLink();
}
}
}
public void AddLink(ILink link)
{
_Links.Add(link);
}
}
}
``` |
2dd0ee6c-41be-485a-9344-91aa2706899d | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels
{
public static class TestModel
{
public static IModel Model
{
get
{
var model = new Model();
var builder = new ModelBuilder(model);
builder.Entity<Product>();
builder.Entity<Category>();
var categoryType = model.GetEntityType(typeof(Category));
var productType = model.GetEntityType(typeof(Product));
var categoryFk = productType.GetOrAddForeignKey(productType.GetProperty("ProductCategoryId"), categoryType.GetPrimaryKey());
categoryType.AddNavigation("CategoryProducts", categoryFk, pointsToPrincipal: false);
productType.AddNavigation("ProductCategory", categoryFk, pointsToPrincipal: true);
return model;
}
}
}
}```
Update to use fluent API to fix build break. | ```c#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels
{
public static class TestModel
{
public static IModel Model
{
get
{
var model = new Model();
var builder = new ModelBuilder(model);
builder.Entity<Product>();
builder.Entity<Category>()
.OneToMany(e => e.CategoryProducts, e => e.ProductCategory)
.ForeignKey(e => e.ProductCategoryId);
return model;
}
}
}
}``` |
9c920021-0719-479f-b2ab-371452d6540e | {
"language": "C#"
} | ```c#
using ChessDotNet;
using ChessVariantsTraining.Models.Variant960;
namespace ChessVariantsTraining.MemoryRepositories.Variant960
{
public interface IGameRepoForSocketHandlers
{
Game Get(string id);
void RegisterMove(Game subject, Move move);
void RegisterGameOutcome(Game subject, string outcome);
}
}
```
Add Register*ChatMessage methods to interface | ```c#
using ChessDotNet;
using ChessVariantsTraining.Models.Variant960;
namespace ChessVariantsTraining.MemoryRepositories.Variant960
{
public interface IGameRepoForSocketHandlers
{
Game Get(string id);
void RegisterMove(Game subject, Move move);
void RegisterGameOutcome(Game subject, string outcome);
void RegisterPlayerChatMessage(Game subject, ChatMessage msg);
void RegisterSpectatorChatMessage(Game subject, ChatMessage msg);
}
}
``` |
fbdef7d3-17c4-4487-83b9-ef8e8837638f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketServiceCore.Command;
using System.Diagnostics;
namespace RemoteProcessService.Command
{
public class LIST : ICommand<RemotePrcessSession>
{
#region ICommand<RemotePrcessSession> Members
public void Execute(RemotePrcessSession session, CommandInfo commandData)
{
Process[] processes;
string firstParam = commandData.GetFirstParam();
if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
processes = Process.GetProcesses();
else
processes = Process.GetProcesses().Where(p =>
p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in processes)
{
sb.AppendLine(string.Format("{0}\t{1}\t{2}", p.ProcessName, p.Id, p.TotalProcessorTime));
}
sb.AppendLine();
session.SendResponse(sb.ToString());
}
#endregion
}
}
```
Fix access denied issue when access process information in RemoteProcessService | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketServiceCore.Command;
using System.Diagnostics;
namespace RemoteProcessService.Command
{
public class LIST : ICommand<RemotePrcessSession>
{
#region ICommand<RemotePrcessSession> Members
public void Execute(RemotePrcessSession session, CommandInfo commandData)
{
Process[] processes;
string firstParam = commandData.GetFirstParam();
if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
processes = Process.GetProcesses();
else
processes = Process.GetProcesses().Where(p =>
p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in processes)
{
sb.AppendLine(string.Format("{0}\t{1}", p.ProcessName, p.Id));
}
sb.AppendLine();
session.SendResponse(sb.ToString());
}
#endregion
}
}
``` |
552417e6-f4fd-44bd-be71-234d92da411c | {
"language": "C#"
} | ```c#
@using Mvc.JQuery.Datatables
@model DataTableVm
<table id="@Model.Id" class="display" >
<thead>
<tr>
@foreach (var column in Model.Columns)
{
<th>@column</th>
}
</tr>
<tr>
@foreach (var column in Model.Columns)
{
<th>@column</th>
}
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">
Loading data from server
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
var $table = $('#@Model.Id');
var dt = $table.dataTable({
"bProcessing": true,
"bStateSave": true,
"bServerSide": true,
"sAjaxSource": "@Html.Raw(Model.AjaxUrl)",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
@if(Model.ColumnFilter){
@:dt.columnFilter({ sPlaceHolder: "head:before" });
}
});
</script>
```
Hide row when ColumnFilter is false | ```c#
@using Mvc.JQuery.Datatables
@model DataTableVm
<table id="@Model.Id" class="display" >
<thead>
<tr>
@foreach (var column in Model.Columns)
{
<th>@column</th>
}
</tr>
@if (Model.ColumnFilter)
{
<tr>
@foreach (var column in Model.Columns)
{
<th>@column</th>
}
</tr>
}
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">
Loading data from server
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
var $table = $('#@Model.Id');
var dt = $table.dataTable({
"bProcessing": true,
"bStateSave": true,
"bServerSide": true,
"sAjaxSource": "@Html.Raw(Model.AjaxUrl)",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
@if(Model.ColumnFilter){
@:dt.columnFilter({ sPlaceHolder: "head:before" });
}
});
</script>
``` |
863cafe2-81ce-47f6-bfca-dc6eae54a92d | {
"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.Containers;
using osu.Game.Graphics;
using osu.Game.Screens.Select.Leaderboards;
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Overlays.BeatmapSet.Scores
{
public class NoScoresPlaceholder : Container
{
private readonly SpriteText text;
public NoScoresPlaceholder()
{
AutoSizeAxes = Axes.Both;
Child = text = new SpriteText
{
Font = OsuFont.GetFont(),
};
}
public void UpdateText(BeatmapLeaderboardScope scope)
{
switch (scope)
{
default:
case BeatmapLeaderboardScope.Global:
text.Text = @"No scores yet. Maybe should try setting some?";
return;
case BeatmapLeaderboardScope.Friend:
text.Text = @"None of your friends has set a score on this map yet!";
return;
case BeatmapLeaderboardScope.Country:
text.Text = @"No one from your country has set a score on this map yet!";
return;
}
}
}
}
```
Fix incorrect formatting for switch/case | ```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.Containers;
using osu.Game.Graphics;
using osu.Game.Screens.Select.Leaderboards;
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Overlays.BeatmapSet.Scores
{
public class NoScoresPlaceholder : Container
{
private readonly SpriteText text;
public NoScoresPlaceholder()
{
AutoSizeAxes = Axes.Both;
Child = text = new SpriteText
{
Font = OsuFont.GetFont(),
};
}
public void UpdateText(BeatmapLeaderboardScope scope)
{
switch (scope)
{
default:
case BeatmapLeaderboardScope.Global:
text.Text = @"No scores yet. Maybe should try setting some?";
return;
case BeatmapLeaderboardScope.Friend:
text.Text = @"None of your friends has set a score on this map yet!";
return;
case BeatmapLeaderboardScope.Country:
text.Text = @"No one from your country has set a score on this map yet!";
return;
}
}
}
}
``` |
0369d95e-3734-4e68-b334-fa9a43f4d320 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
namespace Serilog.Settings.Configuration.Assemblies
{
abstract class AssemblyFinder
{
public abstract IReadOnlyList<AssemblyName> FindAssembliesContainingName(string nameToFind);
protected static bool IsCaseInsensitiveMatch(string text, string textToFind)
{
return text != null && text.ToLowerInvariant().Contains(textToFind.ToLowerInvariant());
}
public static AssemblyFinder Auto()
{
if (Assembly.GetEntryAssembly() != null)
{
return new DependencyContextAssemblyFinder(DependencyContext.Default);
}
return new DllScanningAssemblyFinder();
}
public static AssemblyFinder ForSource(ConfigurationAssemblySource configurationAssemblySource)
{
switch (configurationAssemblySource)
{
case ConfigurationAssemblySource.UseLoadedAssemblies:
return Auto();
case ConfigurationAssemblySource.AlwaysScanDllFiles:
return new DllScanningAssemblyFinder();
default:
throw new ArgumentOutOfRangeException(nameof(configurationAssemblySource), configurationAssemblySource, null);
}
}
public static AssemblyFinder ForDependencyContext(DependencyContext dependencyContext)
{
return new DependencyContextAssemblyFinder(dependencyContext);
}
}
}
```
Add comments explaining behavior of DependencyContext.Default | ```c#
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
namespace Serilog.Settings.Configuration.Assemblies
{
abstract class AssemblyFinder
{
public abstract IReadOnlyList<AssemblyName> FindAssembliesContainingName(string nameToFind);
protected static bool IsCaseInsensitiveMatch(string text, string textToFind)
{
return text != null && text.ToLowerInvariant().Contains(textToFind.ToLowerInvariant());
}
public static AssemblyFinder Auto()
{
// Need to check `Assembly.GetEntryAssembly()` first because
// `DependencyContext.Default` throws an exception when `Assembly.GetEntryAssembly()` returns null
if (Assembly.GetEntryAssembly() != null && DependencyContext.Default != null)
{
return new DependencyContextAssemblyFinder(DependencyContext.Default);
}
return new DllScanningAssemblyFinder();
}
public static AssemblyFinder ForSource(ConfigurationAssemblySource configurationAssemblySource)
{
switch (configurationAssemblySource)
{
case ConfigurationAssemblySource.UseLoadedAssemblies:
return Auto();
case ConfigurationAssemblySource.AlwaysScanDllFiles:
return new DllScanningAssemblyFinder();
default:
throw new ArgumentOutOfRangeException(nameof(configurationAssemblySource), configurationAssemblySource, null);
}
}
public static AssemblyFinder ForDependencyContext(DependencyContext dependencyContext)
{
return new DependencyContextAssemblyFinder(dependencyContext);
}
}
}
``` |
8ac85135-3cf4-447f-9e80-ee641c5fa405 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class UserInputManagerTest : TestCase
{
[Test]
public void IsAliveTest()
{
AddAssert("UserInputManager is alive", () =>
{
using (var client = new TestHeadlessGameHost(@"client", true))
{
return client.CurrentRoot.IsAlive;
}
});
}
private class TestHeadlessGameHost : HeadlessGameHost
{
public Drawable CurrentRoot => Root;
public TestHeadlessGameHost(string hostname, bool bindIPC)
: base(hostname, bindIPC)
{
using (var game = new TestGame())
{
Root = game.CreateUserInputManager();
}
}
}
}
}
```
Make UserInputManager test much more simple | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Input;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class UserInputManagerTest : TestCase
{
[Test]
public void IsAliveTest()
{
AddAssert("UserInputManager is alive", () => new UserInputManager().IsAlive);
}
}
}
``` |
4b02d7df-1cf5-4873-95b0-2bf2a4e8828c | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Objects.Drawables;
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.UI
{
/// <summary>
/// Text that is shown as judgement when a hit object is hit or missed.
/// </summary>
public class DrawableTaikoJudgement : DrawableJudgement
{
/// <summary>
/// Creates a new judgement text.
/// </summary>
/// <param name="judgedObject">The object which is being judged.</param>
/// <param name="result">The judgement to visualise.</param>
public DrawableTaikoJudgement(JudgementResult result, DrawableHitObject judgedObject)
: base(result, judgedObject)
{
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
switch (Result.Type)
{
case HitResult.Ok:
JudgementBody.Colour = colours.GreenLight;
break;
case HitResult.Great:
JudgementBody.Colour = colours.BlueLight;
break;
}
}
protected override void ApplyHitAnimations()
{
this.MoveToY(-100, 500);
base.ApplyHitAnimations();
}
}
}
```
Remove unnecessary local definition of colour logic from taiko judgement | ```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.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Rulesets.Taiko.UI
{
/// <summary>
/// Text that is shown as judgement when a hit object is hit or missed.
/// </summary>
public class DrawableTaikoJudgement : DrawableJudgement
{
/// <summary>
/// Creates a new judgement text.
/// </summary>
/// <param name="judgedObject">The object which is being judged.</param>
/// <param name="result">The judgement to visualise.</param>
public DrawableTaikoJudgement(JudgementResult result, DrawableHitObject judgedObject)
: base(result, judgedObject)
{
}
protected override void ApplyHitAnimations()
{
this.MoveToY(-100, 500);
base.ApplyHitAnimations();
}
}
}
``` |
b4fb4dcd-93e7-49c2-8642-ad1e54df8252 | {
"language": "C#"
} | ```c#
using OpenKh.Kh2;
using OpenKh.Kh2.Messages;
using System.Collections.Generic;
using System.Linq;
namespace OpenKh.Engine
{
public class Kh2MessageProvider : IMessageProvider
{
private List<Msg.Entry> _messages;
public IMessageEncoder Encoder { get; set; } = Encoders.InternationalSystem;
public byte[] GetMessage(ushort id)
{
var message = _messages?.FirstOrDefault(x => x.Id == (id & 0x7fff));
if (message == null)
{
if (id == Msg.FallbackMessage)
return new byte[0];
return GetMessage(Msg.FallbackMessage);
}
return message.Data;
}
public string GetString(ushort id) =>
MsgSerializer.SerializeText(Encoder.Decode(GetMessage(id)));
public void SetString(ushort id, string text)
{
var message = _messages?.FirstOrDefault(x => x.Id == (id & 0x7fff));
if (message == null)
return;
message.Data = Encoder.Encode(MsgSerializer.DeserializeText(text).ToList());
}
public void Load(List<Msg.Entry> entries) =>
_messages = entries;
}
}
```
Improve performance when getting a KH2 message | ```c#
using OpenKh.Kh2;
using OpenKh.Kh2.Messages;
using System.Collections.Generic;
using System.Linq;
namespace OpenKh.Engine
{
public class Kh2MessageProvider : IMessageProvider
{
private Dictionary<int, byte[]> _messages = new Dictionary<int, byte[]>();
public IMessageEncoder Encoder { get; set; } = Encoders.InternationalSystem;
public byte[] GetMessage(ushort id)
{
if (_messages.TryGetValue(id & 0x7fff, out var data))
return data;
if (_messages.TryGetValue(Msg.FallbackMessage, out data))
return data;
return new byte[0];
}
public string GetString(ushort id) =>
MsgSerializer.SerializeText(Encoder.Decode(GetMessage(id)));
public void SetString(ushort id, string text) =>
_messages[id] = Encoder.Encode(MsgSerializer.DeserializeText(text).ToList());
public void Load(List<Msg.Entry> entries) =>
_messages = entries.ToDictionary(x => x.Id, x => x.Data);
}
}
``` |
f9cd9e12-220c-4e44-ba19-0dc80b247445 | {
"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 osu.Framework.Input.Bindings;
using osu.Game.Rulesets;
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;
namespace osu.Game.Input.Bindings
{
[Table("KeyBinding")]
public class DatabasedKeyBinding : KeyBinding
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[ForeignKey(typeof(RulesetInfo))]
public int? RulesetID { get; set; }
[Indexed]
public int? Variant { get; set; }
[Column("Keys")]
public string KeysString
{
get { return KeyCombination.ToString(); }
private set { KeyCombination = value; }
}
[Column("Action")]
public new int Action
{
get { return (int)base.Action; }
set { base.Action = value; }
}
}
}```
Add index to Action column | ```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 osu.Framework.Input.Bindings;
using osu.Game.Rulesets;
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;
namespace osu.Game.Input.Bindings
{
[Table("KeyBinding")]
public class DatabasedKeyBinding : KeyBinding
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[ForeignKey(typeof(RulesetInfo))]
public int? RulesetID { get; set; }
[Indexed]
public int? Variant { get; set; }
[Column("Keys")]
public string KeysString
{
get { return KeyCombination.ToString(); }
private set { KeyCombination = value; }
}
[Indexed]
[Column("Action")]
public new int Action
{
get { return (int)base.Action; }
set { base.Action = value; }
}
}
}``` |
e1f93df7-9103-4ab3-a057-071769e87694 | {
"language": "C#"
} | ```c#
using CppSharp;
using CppSharp.Generators;
namespace MonoEmbeddinator4000
{
public enum CompilationTarget
{
SharedLibrary,
StaticLibrary,
Application
}
public class Options
{
public Options()
{
Project = new Project();
GenerateSupportFiles = true;
}
public Project Project;
// Generator options
public string LibraryName;
public GeneratorKind Language;
public TargetPlatform Platform;
/// <summary>
/// Specifies the VS version.
/// </summary>
/// <remarks>When null, latest is used.</remarks>
public VisualStudioVersion VsVersion;
// If code compilation is enabled, then sets the compilation target.
public CompilationTarget Target;
public string OutputNamespace;
public string OutputDir;
// If true, will force the generation of debug metadata for the native
// and managed code.
public bool DebugMode;
// If true, will use unmanaged->managed thunks to call managed methods.
// In this mode the JIT will generate specialized wrappers for marshaling
// which will be faster but also lead to higher memory consumption.
public bool UseUnmanagedThunks;
// If true, will generate support files alongside generated binding code.
public bool GenerateSupportFiles;
// If true, will try to compile the generated managed-to-native binding code.
public bool CompileCode;
// If true, will compile the generated as a shared library / DLL.
public bool CompileSharedLibrary => Target == CompilationTarget.SharedLibrary;
}
}
```
Unify common options with CppSharp. | ```c#
using CppSharp;
using CppSharp.Generators;
namespace MonoEmbeddinator4000
{
public enum CompilationTarget
{
SharedLibrary,
StaticLibrary,
Application
}
public class Options : DriverOptions
{
public Options()
{
Project = new Project();
GenerateSupportFiles = true;
}
public Project Project;
// Generator options
public GeneratorKind Language;
public TargetPlatform Platform;
/// <summary>
/// Specifies the VS version.
/// </summary>
/// <remarks>When null, latest is used.</remarks>
public VisualStudioVersion VsVersion;
// If code compilation is enabled, then sets the compilation target.
public CompilationTarget Target;
// If true, will force the generation of debug metadata for the native
// and managed code.
public bool DebugMode;
// If true, will use unmanaged->managed thunks to call managed methods.
// In this mode the JIT will generate specialized wrappers for marshaling
// which will be faster but also lead to higher memory consumption.
public bool UseUnmanagedThunks;
// If true, will generate support files alongside generated binding code.
public bool GenerateSupportFiles;
// If true, will compile the generated as a shared library / DLL.
public bool CompileSharedLibrary => Target == CompilationTarget.SharedLibrary;
}
}
``` |
d1198ca7-7cbd-4179-8820-8b2b62fdbf04 | {
"language": "C#"
} | ```c#
using Norm.Configuration;
using Norm.BSON;
using System.Collections.Generic;
using System.Linq;
namespace Norm.Responses
{
/// <summary>
/// Represents a message with an Ok status
/// </summary>
public class BaseStatusMessage : IExpando
{
private Dictionary<string, object> _properties = new Dictionary<string, object>(0);
/// <summary>
/// This is the raw value returned from the response.
/// It is required for serializer support, use "WasSuccessful" if you need a boolean value.
/// </summary>
protected double? ok { get; set; }
/// <summary>
/// Did this message return correctly?
/// </summary>
/// <remarks>This maps to the "OK" value of the response.</remarks>
public bool WasSuccessful
{
get
{
return this.ok == 1d ? true : false;
}
}
/// <summary>
/// Additional, non-static properties of this message.
/// </summary>
/// <returns></returns>
public IEnumerable<ExpandoProperty> AllProperties()
{
return this._properties.Select(j => new ExpandoProperty(j.Key, j.Value));
}
public void Delete(string propertyName)
{
this._properties.Remove(propertyName);
}
public object this[string propertyName]
{
get
{
return this._properties[propertyName];
}
set
{
this._properties[propertyName] = value;
}
}
}
}
```
Allow connections to MongoDB 1.5.2+ that now returns 'ok' in the status message as a boolean, not a decimal | ```c#
using Norm.Configuration;
using Norm.BSON;
using System.Collections.Generic;
using System.Linq;
namespace Norm.Responses
{
/// <summary>
/// Represents a message with an Ok status
/// </summary>
public class BaseStatusMessage : IExpando
{
private Dictionary<string, object> _properties = new Dictionary<string, object>(0);
/// <summary>
/// This is the raw value returned from the response.
/// It is required for serializer support, use "WasSuccessful" if you need a boolean value.
/// </summary>
/// <remarks>This maps to the "OK" value of the response which can be a decimal (pre-1.5.2) or boolean (1.5.2+).</remarks>
public bool WasSuccessful
{
get
{
return this["ok"].Equals(true) || this["ok"].Equals(1d);
}
}
/// <summary>
/// Additional, non-static properties of this message.
/// </summary>
/// <returns></returns>
public IEnumerable<ExpandoProperty> AllProperties()
{
return this._properties.Select(j => new ExpandoProperty(j.Key, j.Value));
}
public void Delete(string propertyName)
{
this._properties.Remove(propertyName);
}
public object this[string propertyName]
{
get
{
return this._properties[propertyName];
}
set
{
this._properties[propertyName] = value;
}
}
}
}
``` |
a820d7ea-ca90-4d55-8874-32c3e73ac058 | {
"language": "C#"
} | ```c#
using LanguageExt.Effects.Traits;
namespace LanguageExt.Sys.Traits
{
/// <summary>
/// Convenience trait - captures the BCL IO behaviour
/// </summary>
/// <typeparam name="RT">Runtime</typeparam>
public interface HasSys<RT> :
HasCancel<RT>,
HasConsole<RT>,
HasEncoding<RT>,
HasFile<RT>,
HasTextRead<RT>,
HasTime<RT>
where RT :
struct,
HasCancel<RT>,
HasConsole<RT>,
HasFile<RT>,
HasTextRead<RT>,
HasTime<RT>,
HasEncoding<RT>
{
}
}
```
Add HasDirectory trait to HasSys trait | ```c#
using LanguageExt.Effects.Traits;
namespace LanguageExt.Sys.Traits
{
/// <summary>
/// Convenience trait - captures the BCL IO behaviour
/// </summary>
/// <typeparam name="RT">Runtime</typeparam>
public interface HasSys<RT> :
HasCancel<RT>,
HasConsole<RT>,
HasEncoding<RT>,
HasFile<RT>,
HasDirectory<RT>,
HasTextRead<RT>,
HasTime<RT>
where RT :
struct,
HasCancel<RT>,
HasConsole<RT>,
HasFile<RT>,
HasDirectory<RT>,
HasTextRead<RT>,
HasTime<RT>,
HasEncoding<RT>
{
}
}
``` |
1aaaeae2-d075-4945-ad8e-71b09c98b11d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
namespace CreateXMLFile
{
internal static class Program
{
private static void Main()
{
const string fileName = "quotes.txt";
Dictionary<string, string> dicoQuotes = new Dictionary<string, string>();
List<string> quotesList = new List<string>();
StreamReader sr = new StreamReader(fileName);
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
quotesList.Add(line);
}
}
}
}```
Load list of quotes into a dictionary | ```c#
using System;
using System.Collections.Generic;
using System.IO;
namespace CreateXMLFile
{
internal static class Program
{
private static void Main()
{
const string fileName = "quotes.txt";
Dictionary<string, string> dicoQuotes = new Dictionary<string, string>();
List<string> quotesList = new List<string>();
StreamReader sr = new StreamReader(fileName);
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
quotesList.Add(line);
}
for (int i = 0; i < quotesList.Count; i = i + 2)
{
if (!dicoQuotes.ContainsKey(quotesList[i]))
{
dicoQuotes.Add(quotesList[i], quotesList[i + 1]);
}
else
{
Console.WriteLine(quotesList[i]);
}
}
Console.WriteLine("Press a key to exit:");
Console.ReadKey();
}
}
}``` |
c2f727bc-c5a0-4b69-8e82-ced66d2f49bf | {
"language": "C#"
} | ```c#
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent
{
public class ViewLocator : IDataTemplate
{
public bool SupportsRecycling => false;
public IControl Build(object data)
{
var name = data.GetType().FullName!.Replace("ViewModel", "View");
var type = Type.GetType(name);
if (type != null)
{
var result = Activator.CreateInstance(type) as Control;
if (result is null)
{
throw new Exception($"Unable to activate type: {type}");
}
return result;
}
else
{
return new TextBlock { Text = "Not Found: " + name };
}
}
public bool Match(object data)
{
return data is ViewModelBase;
}
}
}```
Remove unused property from view locator | ```c#
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent
{
public class ViewLocator : IDataTemplate
{
public IControl Build(object data)
{
var name = data.GetType().FullName!.Replace("ViewModel", "View");
var type = Type.GetType(name);
if (type != null)
{
var result = Activator.CreateInstance(type) as Control;
if (result is null)
{
throw new Exception($"Unable to activate type: {type}");
}
return result;
}
else
{
return new TextBlock { Text = "Not Found: " + name };
}
}
public bool Match(object data)
{
return data is ViewModelBase;
}
}
}``` |
7dbc3029-d105-4cad-9277-1b1f9c6d1b39 | {
"language": "C#"
} | ```c#
using Octokit.Internal;
namespace Octokit
{
public interface IGitHubClient
{
IConnection Connection { get; }
IAuthorizationsClient Authorization { get; }
IIssuesClient Issue { get; }
IMiscellaneousClient Miscellaneous { get; }
IOrganizationsClient Organization { get; }
IRepositoriesClient Repository { get; }
IReleasesClient Release { get; }
ISshKeysClient SshKey { get; }
IUsersClient User { get; }
INotificationsClient Notification { get; }
}
}
```
Add TagsClient to GitHubClient inteface | ```c#
using Octokit.Internal;
namespace Octokit
{
public interface IGitHubClient
{
IConnection Connection { get; }
IAuthorizationsClient Authorization { get; }
IIssuesClient Issue { get; }
IMiscellaneousClient Miscellaneous { get; }
IOrganizationsClient Organization { get; }
IRepositoriesClient Repository { get; }
IReleasesClient Release { get; }
ISshKeysClient SshKey { get; }
IUsersClient User { get; }
INotificationsClient Notification { get; }
ITagsClient Tag { get; }
}
}
``` |
ab578bfd-d491-432c-91ae-6ae34ce649fa | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays.Dialog
{
public class PopupDialogDangerousButton : PopupDialogButton
{
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
ButtonColour = colours.Red3;
ColourContainer.Add(new ConfirmFillBox
{
Action = () => Action(),
RelativeSizeAxes = Axes.Both,
Blending = BlendingParameters.Additive,
});
}
private class ConfirmFillBox : HoldToConfirmContainer
{
private Box box;
protected override double? HoldActivationDelay => 500;
protected override void LoadComplete()
{
base.LoadComplete();
Child = box = new Box
{
RelativeSizeAxes = Axes.Both,
};
Progress.BindValueChanged(progress => box.Width = (float)progress.NewValue, true);
}
protected override bool OnMouseDown(MouseDownEvent e)
{
BeginConfirm();
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
if (!e.HasAnyButtonPressed)
AbortConfirm();
}
}
}
}
```
Fix dialog dangerous button being clickable at edges | ```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.Shapes;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays.Dialog
{
public class PopupDialogDangerousButton : PopupDialogButton
{
private Box progressBox;
private DangerousConfirmContainer confirmContainer;
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
ButtonColour = colours.Red3;
ColourContainer.Add(progressBox = new Box
{
RelativeSizeAxes = Axes.Both,
Blending = BlendingParameters.Additive,
});
AddInternal(confirmContainer = new DangerousConfirmContainer
{
Action = () => Action(),
RelativeSizeAxes = Axes.Both,
});
}
protected override void LoadComplete()
{
base.LoadComplete();
confirmContainer.Progress.BindValueChanged(progress => progressBox.Width = (float)progress.NewValue, true);
}
private class DangerousConfirmContainer : HoldToConfirmContainer
{
protected override double? HoldActivationDelay => 500;
protected override bool OnMouseDown(MouseDownEvent e)
{
BeginConfirm();
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
if (!e.HasAnyButtonPressed)
AbortConfirm();
}
}
}
}
``` |
5d42e31b-24b5-4e6c-9c41-e6a4d20529e7 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// The current overall state of a realtime multiplayer room.
/// </summary>
public enum MultiplayerRoomState
{
Open,
WaitingForLoad,
Playing,
WaitingForResults,
Closed
}
}
```
Document room states and remove unnecessary WaitingForResults state | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// The current overall state of a realtime multiplayer room.
/// </summary>
public enum MultiplayerRoomState
{
/// <summary>
/// The room is open and accepting new players.
/// </summary>
Open,
/// <summary>
/// A game start has been triggered but players have not finished loading.
/// </summary>
WaitingForLoad,
/// <summary>
/// A game is currently ongoing.
/// </summary>
Playing,
/// <summary>
/// The room has been disbanded and closed.
/// </summary>
Closed
}
}
``` |
3d794f07-f209-4c59-a34c-7d8651d40a71 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Insula.Common;
namespace DeploymentCockpit.Common
{
public static class VariableHelper
{
public const string ProductVersionVariable = "ProductVersion";
public const string TargetComputerNameVariable = "Target.ComputerName";
public const string CredentialUsernameVariable = "Credential.Username";
public const string CredentialPasswordVariable = "Credential.Password";
public static string FormatPlaceholder(string variableName)
{
return "{0}{1}{2}".FormatString(
DomainContext.VariablePlaceholderPrefix,
variableName,
DomainContext.VariablePlaceholderSuffix);
}
}
}
```
Remove dots from built in variables | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Insula.Common;
namespace DeploymentCockpit.Common
{
public static class VariableHelper
{
public const string ProductVersionVariable = "ProductVersion";
public const string TargetComputerNameVariable = "TargetComputerName";
public const string CredentialUsernameVariable = "CredentialUsername";
public const string CredentialPasswordVariable = "CredentialPassword";
public static string FormatPlaceholder(string variableName)
{
return "{0}{1}{2}".FormatString(
DomainContext.VariablePlaceholderPrefix,
variableName,
DomainContext.VariablePlaceholderSuffix);
}
}
}
``` |
af2d44c6-1546-40e5-b62f-aa0e207d0a9d | {
"language": "C#"
} | ```c#
using System;
using UIKit;
namespace PureLayout.Net
{
public partial class UIViewPureLayout
{
public static NSLayoutConstraint[] AutoPinEdgesToSuperviewEdgesExcludingEdge(this UIView view, ALEdge excludingEdge)
{
return view.AutoPinEdgesToSuperviewEdgesExcludingEdge(ALHelpers.ALEdgeInsetsZero, excludingEdge);
}
}
}
```
Add extension methods for pinning to top and bottom layout guide | ```c#
using System;
using UIKit;
namespace PureLayout.Net
{
public partial class UIViewPureLayout
{
public static NSLayoutConstraint[] AutoPinEdgesToSuperviewEdgesExcludingEdge(this UIView view, ALEdge excludingEdge)
{
return view.AutoPinEdgesToSuperviewEdgesExcludingEdge(ALHelpers.ALEdgeInsetsZero, excludingEdge);
}
public static NSLayoutConstraint AutoPinToBottomLayoutGuideOfViewController(this UIView view, UIViewController viewController)
{
return view.AutoPinToBottomLayoutGuideOfViewController(viewController, 0f);
}
public static NSLayoutConstraint AutoPinToTopLayoutGuideOfViewController(this UIView view, UIViewController viewController)
{
return view.AutoPinToTopLayoutGuideOfViewController(viewController, 0f);
}
}
}
``` |
70521e5b-8c58-44d4-8205-fd8eecabf7d0 | {
"language": "C#"
} | ```c#
/// <summary>
/// Credit card type.
/// </summary>
namespace CreditCardProcessing
{
using System.ComponentModel;
/// <summary>
/// Credit card type.
/// </summary>
public enum CreditCardType
{
/// <summary>
/// Unknown issuers.
/// </summary>
[Description("Unknown Issuer")]
Unknown,
/// <summary>
/// American Express.
/// </summary>
[Description("American Express")]
AmEx,
/// <summary>
/// Discover Card.
/// </summary>
[Description("Discover Card")]
Discover,
/// <summary>
/// Master Card.
/// </summary>
[Description("MasterCard")]
MasterCard,
/// <summary>
/// Visa.
/// </summary>
[Description("Visa")]
Visa,
}
}```
Clean up whitespace and file header on type enumeration | ```c#
//-----------------------------------------------------------------------
// <copyright file="CreditCardType.cs" company="Colagioia Industries">
// Provided under the terms of the AGPL v3.
// </copyright>
//-----------------------------------------------------------------------
/// <summary>
/// Credit card type.
/// </summary>
namespace CreditCardProcessing
{
using System.ComponentModel;
/// <summary>
/// Credit card type.
/// </summary>
public enum CreditCardType
{
/// <summary>
/// Unknown issuers.
/// </summary>
[Description("Unknown Issuer")]
Unknown,
/// <summary>
/// American Express cards.
/// </summary>
[Description("American Express")]
AmEx,
/// <summary>
/// Discover Card cards.
/// </summary>
[Description("Discover Card")]
Discover,
/// <summary>
/// MasterCard cards.
/// </summary>
[Description("MasterCard")]
MasterCard,
/// <summary>
/// Visa cards.
/// </summary>
[Description("Visa")]
Visa,
}
}``` |
c34536db-8e39-4f90-9662-c9c9760ab4fd | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Storage
{
internal static class StorageOptions
{
internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\";
public const string OptionName = "FeatureManager/Storage";
public static readonly Option<StorageDatabase> Database = new(OptionName, nameof(Database), defaultValue: StorageDatabase.CloudCache);
public static readonly Option<bool> DatabaseMustSucceed = new(OptionName, nameof(DatabaseMustSucceed), defaultValue: false);
public static readonly Option<bool> PrintDatabaseLocation = new(OptionName, nameof(PrintDatabaseLocation), defaultValue: false);
}
[ExportOptionProvider, Shared]
internal class RemoteHostOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoteHostOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
StorageOptions.Database,
StorageOptions.DatabaseMustSucceed,
StorageOptions.PrintDatabaseLocation);
}
}
```
Set default back to sqlite | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Storage
{
internal static class StorageOptions
{
internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\";
public const string OptionName = "FeatureManager/Storage";
public static readonly Option<StorageDatabase> Database = new(OptionName, nameof(Database), defaultValue: StorageDatabase.SQLite);
public static readonly Option<bool> DatabaseMustSucceed = new(OptionName, nameof(DatabaseMustSucceed), defaultValue: false);
public static readonly Option<bool> PrintDatabaseLocation = new(OptionName, nameof(PrintDatabaseLocation), defaultValue: false);
}
[ExportOptionProvider, Shared]
internal class RemoteHostOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoteHostOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
StorageOptions.Database,
StorageOptions.DatabaseMustSucceed,
StorageOptions.PrintDatabaseLocation);
}
}
``` |
8d4c17e1-3988-4f9a-b1a9-15dc73f8fb42 | {
"language": "C#"
} | ```c#
using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;
using Raven.Client;
using Raven.Client.Embedded;
namespace CGO.Web.NinjectModules
{
public class RavenModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope();
Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
private static IDocumentStore InitialiseDocumentStore()
{
var documentStore = new EmbeddableDocumentStore
{
DataDirectory = "CGO.raven",
UseEmbeddedHttpServer = true
};
documentStore.InitializeProfiling();
documentStore.Initialize();
return documentStore;
}
}
}```
Fix RavenConfiguration for Embedded mode. | ```c#
using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;
using Raven.Client;
using Raven.Client.Embedded;
namespace CGO.Web.NinjectModules
{
public class RavenModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope();
Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
private static IDocumentStore InitialiseDocumentStore()
{
var documentStore = new EmbeddableDocumentStore
{
DataDirectory = "CGO.raven",
UseEmbeddedHttpServer = true,
Configuration = { Port = 28645 }
};
documentStore.InitializeProfiling();
documentStore.Initialize();
return documentStore;
}
}
}``` |
c5fb4d9f-85f2-407c-b370-f4e8542ee9e0 | {
"language": "C#"
} | ```c#
@model string
@section Title{
Message
}
<h2>@ViewBag.StatusMessage</h2>
```
Fix "change password message" view | ```c#
@model string
@section Title{
Message
}
<h2>@Model</h2>
``` |
1384e425-21f3-4042-9ea5-045bc82f6323 | {
"language": "C#"
} | ```c#
#region Copyright
// Copyright 2016 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace SnapMD.VirtualCare.ApiModels
{
public class SerializableToken
{
public string access_token { get; set; }
}
}
```
Add expiration to token response | ```c#
#region Copyright
// Copyright 2016 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
namespace SnapMD.VirtualCare.ApiModels
{
public class SerializableToken
{
public string access_token { get; set; }
public DateTimeOffset? expires { get; set; }
}
}
``` |
1779e666-e0e1-4531-adea-7aa5343f4cc2 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
namespace FluentNHibernate.Framework
{
public interface ISessionSource
{
ISession CreateSession();
void BuildSchema();
PersistenceModel Model { get; }
}
public class SessionSource : ISessionSource
{
private ISessionFactory _sessionFactory;
private Configuration _configuration;
private PersistenceModel _model;
public SessionSource(IDictionary<string, string> properties, PersistenceModel model)
{
_configuration = new Configuration();
_configuration.AddProperties(properties);
model.Configure(_configuration);
_model = model;
_sessionFactory = _configuration.BuildSessionFactory();
}
public PersistenceModel Model
{
get { return _model; }
}
public ISession CreateSession()
{
return _sessionFactory.OpenSession();
}
public void BuildSchema()
{
ISession session = CreateSession();
IDbConnection connection = session.Connection;
string[] drops = _configuration.GenerateDropSchemaScript(Dialect.GetDialect());
executeScripts(drops, connection);
string[] scripts = _configuration.GenerateSchemaCreationScript(Dialect.GetDialect());
executeScripts(scripts, connection);
}
private static void executeScripts(string[] scripts, IDbConnection connection)
{
foreach (var script in scripts)
{
IDbCommand command = connection.CreateCommand();
command.CommandText = script;
command.ExecuteNonQuery();
}
}
}
}```
Put back to match nhibernate in svn. | ```c#
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace FluentNHibernate.Framework
{
public interface ISessionSource
{
ISession CreateSession();
void BuildSchema();
PersistenceModel Model { get; }
}
public class SessionSource : ISessionSource
{
private ISessionFactory _sessionFactory;
private Configuration _configuration;
private PersistenceModel _model;
public SessionSource(IDictionary<string, string> properties, PersistenceModel model)
{
_configuration = new Configuration();
_configuration.AddProperties(properties);
model.Configure(_configuration);
_model = model;
_sessionFactory = _configuration.BuildSessionFactory();
}
public PersistenceModel Model
{
get { return _model; }
}
public ISession CreateSession()
{
return _sessionFactory.OpenSession();
}
public void BuildSchema()
{
ISession session = CreateSession();
IDbConnection connection = session.Connection;
string[] drops = _configuration.GenerateDropSchemaScript(_sessionFactory.Dialect);
executeScripts(drops, connection);
string[] scripts = _configuration.GenerateSchemaCreationScript(_sessionFactory.Dialect);
executeScripts(scripts, connection);
}
private static void executeScripts(string[] scripts, IDbConnection connection)
{
foreach (var script in scripts)
{
IDbCommand command = connection.CreateCommand();
command.CommandText = script;
command.ExecuteNonQuery();
}
}
}
}``` |
e471c92d-595f-4b42-a97f-80c38c245512 | {
"language": "C#"
} | ```c#
#region Copyright (c) 2016 Atif Aziz. 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 WebLinq.Sys
{
using System;
using System.Collections.Generic;
using System.Linq;
using Mannex.Collections.Generic;
public static class SysQuery
{
public static Query<string> Spawn(string path, string args) =>
Spawn(path, args, output => output, null);
public static Query<KeyValuePair<T, string>> Spawn<T>(string path, string args, T stdoutKey, T stderrKey) =>
Spawn(path, args, stdout => stdoutKey.AsKeyTo(stdout),
stderr => stderrKey.AsKeyTo(stderr));
public static Query<T> Spawn<T>(string path, string args, Func<string, T> stdoutSelector, Func<string, T> stderrSelector) =>
Query.Create(context => QueryResult.Create(from e in context.Eval((ISpawnService s) => s.Spawn(path, args, stdoutSelector, stderrSelector))
select QueryResultItem.Create(context, e)));
}
}
```
Leverage query syntax for cleaner Spawn implementation | ```c#
#region Copyright (c) 2016 Atif Aziz. 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 WebLinq.Sys
{
using System;
using System.Collections.Generic;
using Mannex.Collections.Generic;
public static class SysQuery
{
public static Query<string> Spawn(string path, string args) =>
Spawn(path, args, output => output, null);
public static Query<KeyValuePair<T, string>> Spawn<T>(string path, string args, T stdoutKey, T stderrKey) =>
Spawn(path, args, stdout => stdoutKey.AsKeyTo(stdout),
stderr => stderrKey.AsKeyTo(stderr));
public static Query<T> Spawn<T>(string path, string args, Func<string, T> stdoutSelector, Func<string, T> stderrSelector) =>
from s in Query.GetService<ISpawnService>()
from e in s.Spawn(path, args, stdoutSelector, stderrSelector).ToQuery()
select e;
}
}
``` |
d7075947-8862-49d5-8f2d-a2c0b7eb0ab8 | {
"language": "C#"
} | ```c#
using System.Runtime.InteropServices;
namespace Evolve.Test.Utilities
{
public class PostgreSqlDockerContainer : IDockerContainer
{
private DockerContainer _container;
public string Id => _container.Id;
public string ExposedPort => "5432";
public string HostPort => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "3306" : "3307"; // AppVeyor: 5432 Travis CI: 5433
public string DbName => "my_database";
public string DbPwd => "Password12!"; // AppVeyor
public string DbUser => "postgres";
public bool Start()
{
_container = new DockerContainerBuilder(new DockerContainerBuilderOptions
{
FromImage = "postgres",
Tag = "alpine",
Name = "postgres-evolve",
Env = new[] { $"POSTGRES_PASSWORD={DbPwd}", $"POSTGRES_DB={DbName}" },
ExposedPort = $"{ExposedPort}/tcp",
HostPort = HostPort
}).Build();
return _container.Start();
}
public void Remove() => _container.Remove();
public bool Stop() => _container.Stop();
public void Dispose() => _container.Dispose();
}
}
```
Fix Travis CI / AppVeyor | ```c#
using System.Runtime.InteropServices;
namespace Evolve.Test.Utilities
{
public class PostgreSqlDockerContainer : IDockerContainer
{
private DockerContainer _container;
public string Id => _container.Id;
public string ExposedPort => "5432";
public string HostPort => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "5432" : "5433"; // AppVeyor: 5432 Travis CI: 5433
public string DbName => "my_database";
public string DbPwd => "Password12!"; // AppVeyor
public string DbUser => "postgres";
public bool Start()
{
_container = new DockerContainerBuilder(new DockerContainerBuilderOptions
{
FromImage = "postgres",
Tag = "alpine",
Name = "postgres-evolve",
Env = new[] { $"POSTGRES_PASSWORD={DbPwd}", $"POSTGRES_DB={DbName}" },
ExposedPort = $"{ExposedPort}/tcp",
HostPort = HostPort
}).Build();
return _container.Start();
}
public void Remove() => _container.Remove();
public bool Stop() => _container.Stop();
public void Dispose() => _container.Dispose();
}
}
``` |
c842172f-2179-4e88-9011-2d8f14109b03 | {
"language": "C#"
} | ```c#
using System;
namespace EarTrumpet.Extensions
{
public enum OSVersions : int
{
RS3 = 16299,
RS4 = 17134,
}
public static class OperatingSystemExtensions
{
public static bool IsAtLeast(this OperatingSystem os, OSVersions version)
{
return os.Version.Build >= (int)version;
}
}
}
```
Add an RS5 prerelease build | ```c#
using System;
namespace EarTrumpet.Extensions
{
public enum OSVersions : int
{
RS3 = 16299,
RS4 = 17134,
RS5_Prerelease = 17723,
}
public static class OperatingSystemExtensions
{
public static bool IsAtLeast(this OperatingSystem os, OSVersions version)
{
return os.Version.Build >= (int)version;
}
}
}
``` |
13cba825-1e2f-4c78-b2e0-08c7a09149bf | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Sep.Git.Tfs.Core.TfsInterop;
using Xunit;
namespace Sep.Git.Tfs.Test.Core.TfsInterop
{
public class BranchExtensionsTest
{
[Fact]
public void AllChildrenAlwaysReturnsAnEnumerable()
{
IEnumerable<BranchTree> result = ((BranchTree) null).GetAllChildren();
Assert.NotNull(result);
Assert.Empty(result);
}
}
}```
Add Unit tests for IEnumerable<BranchTree>.GetAllChildren() | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Rhino.Mocks;
using Sep.Git.Tfs.Core.TfsInterop;
using Xunit;
namespace Sep.Git.Tfs.Test.Core.TfsInterop
{
public class BranchExtensionsTest
{
[Fact]
public void AllChildrenAlwaysReturnsAnEnumerable()
{
IEnumerable<BranchTree> result = ((BranchTree) null).GetAllChildren();
Assert.NotNull(result);
Assert.Empty(result);
}
private BranchTree CreateBranchTree(string tfsPath, BranchTree parent = null)
{
var branchObject = MockRepository.GenerateStub<IBranchObject>();
branchObject.Stub(m => m.Path).Return(tfsPath);
var branchTree = new BranchTree(branchObject);
if(parent != null)
parent.ChildBranches.Add(branchTree);
return branchTree;
}
[Fact]
public void WhenGettingChildrenOfTopBranch_ThenReturnAllTheChildren()
{
var trunk = CreateBranchTree("$/Project/Trunk");
var branch1 = CreateBranchTree("$/Project/Branch1", trunk);
var branch2 = CreateBranchTree("$/Project/Branch2", trunk);
var branch3 = CreateBranchTree("$/Project/Branch3", trunk);
IEnumerable<BranchTree> result = trunk.GetAllChildren();
Assert.NotNull(result);
Assert.Equal(3, result.Count());
Assert.Equal(new List<BranchTree> { branch1, branch2, branch3 }, result);
}
[Fact]
public void WhenGettingChildrenOfOneBranch_ThenReturnChildrenOfThisBranch()
{
var trunk = CreateBranchTree("$/Project/Trunk");
var branch1 = CreateBranchTree("$/Project/Branch1", trunk);
var branch1_1 = CreateBranchTree("$/Project/Branch1.1", branch1);
var branch1_2 = CreateBranchTree("$/Project/Branch1.2", branch1);
var branch2 = CreateBranchTree("$/Project/Branch2", trunk);
var branch3 = CreateBranchTree("$/Project/Branch3", trunk);
IEnumerable<BranchTree> result = branch1.GetAllChildren();
Assert.NotNull(result);
Assert.Equal(2, result.Count());
Assert.Equal(new List<BranchTree> { branch1_1, branch1_2 }, result);
}
}
}``` |
a95cc2e0-68b9-4722-a0e7-e16bbc72bb2d | {
"language": "C#"
} | ```c#
using Bugfree.Spo.Cqrs.Core.Utilities;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Bugfree.Spo.Cqrs.Core.Queries
{
public class GetTenantSiteCollections : Query
{
public GetTenantSiteCollections(ILogger l) : base(l) { }
private List<SiteProperties> GetTenantSiteCollectionsRecursive(Tenant tenant, List<SiteProperties> siteProperties, int startPosition)
{
Logger.Verbose($"Fetching tenant site collections starting from position {startPosition}");
var tenantSiteCollections = tenant.GetSiteProperties(startPosition, true);
tenant.Context.Load(tenantSiteCollections);
tenant.Context.ExecuteQuery();
var newSiteProperties = siteProperties.Concat(tenantSiteCollections).ToList();
return tenantSiteCollections.NextStartIndex == -1
? newSiteProperties
: GetTenantSiteCollectionsRecursive(tenant, newSiteProperties, tenantSiteCollections.NextStartIndex);
}
public List<SiteProperties> Execute(ClientContext ctx)
{
Logger.Verbose($"About to execute {nameof(GetTenantSiteCollections)}");
var url = ctx.Url;
var tenantAdminUrl = new AdminUrlInferrer().InferAdminFromTenant(new Uri(url.Replace(new Uri(url).AbsolutePath, "")));
var tenantAdminCtx = new ClientContext(tenantAdminUrl) { Credentials = ctx.Credentials };
var tenant = new Tenant(tenantAdminCtx);
tenantAdminCtx.Load(tenant);
tenantAdminCtx.ExecuteQuery();
return GetTenantSiteCollectionsRecursive(tenant, new List<SiteProperties>(), 0);
}
}
}
```
Remove dependency on admin url mapper | ```c#
using Bugfree.Spo.Cqrs.Core.Utilities;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using System.Collections.Generic;
using System.Linq;
namespace Bugfree.Spo.Cqrs.Core.Queries
{
public class GetTenantSiteCollections : Query
{
public GetTenantSiteCollections(ILogger l) : base(l) { }
private List<SiteProperties> GetTenantSiteCollectionsRecursive(Tenant tenant, List<SiteProperties> siteProperties, int startPosition)
{
Logger.Verbose($"Fetching tenant site collections starting from position {startPosition}");
var tenantSiteCollections = tenant.GetSiteProperties(startPosition, true);
tenant.Context.Load(tenantSiteCollections);
tenant.Context.ExecuteQuery();
var newSiteProperties = siteProperties.Concat(tenantSiteCollections).ToList();
return tenantSiteCollections.NextStartIndex == -1
? newSiteProperties
: GetTenantSiteCollectionsRecursive(tenant, newSiteProperties, tenantSiteCollections.NextStartIndex);
}
public List<SiteProperties> Execute(ClientContext tenantAdminCtx) {
Logger.Verbose($"About to execute {nameof(GetTenantSiteCollections)}");
var tenant = new Tenant(tenantAdminCtx);
tenantAdminCtx.Load(tenant);
tenantAdminCtx.ExecuteQuery();
return GetTenantSiteCollectionsRecursive(tenant, new List<SiteProperties>(), 0);
}
}
}
``` |
77c5dc34-a0ed-4a9e-9bde-dbe462f9f9b0 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osuTK;
namespace osu.Framework.Tests.Primitives
{
[TestFixture]
public class Vector2ExtensionsTest
{
[Test]
public void TestClockwiseOrientation()
{
var vertices = new[]
{
new Vector2(0, 1),
Vector2.One,
new Vector2(1, 0),
Vector2.Zero
};
float orientation = Vector2Extensions.GetOrientation(vertices);
Assert.That(orientation, Is.EqualTo(2).Within(0.001));
}
[Test]
public void TestCounterClockwiseOrientation()
{
var vertices = new[]
{
Vector2.Zero,
new Vector2(1, 0),
Vector2.One,
new Vector2(0, 1),
};
float orientation = Vector2Extensions.GetOrientation(vertices);
Assert.That(orientation, Is.EqualTo(-2).Within(0.001));
}
}
}
```
Improve orientation tests + add quad test | ```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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osuTK;
namespace osu.Framework.Tests.Primitives
{
[TestFixture]
public class Vector2ExtensionsTest
{
[TestCase(true)]
[TestCase(false)]
public void TestArrayOrientation(bool clockwise)
{
var vertices = new[]
{
new Vector2(0, 1),
Vector2.One,
new Vector2(1, 0),
Vector2.Zero
};
if (!clockwise)
Array.Reverse(vertices);
float orientation = Vector2Extensions.GetOrientation(vertices);
Assert.That(orientation, Is.EqualTo(clockwise ? 2 : -2).Within(0.001));
}
[TestCase(true)]
[TestCase(false)]
public void TestQuadOrientation(bool clockwise)
{
Quad quad = clockwise
? new Quad(new Vector2(0, 1), Vector2.One, Vector2.Zero, new Vector2(1, 0))
: new Quad(Vector2.Zero, new Vector2(1, 0), new Vector2(0, 1), Vector2.One);
float orientation = Vector2Extensions.GetOrientation(quad.GetVertices());
Assert.That(orientation, Is.EqualTo(clockwise ? 2 : -2).Within(0.001));
}
}
}
``` |
04c5ac70-72dc-43d6-8219-995a9e254006 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
using System;
[RequireComponent (typeof(CanvasGroup))]
public class Loader : MonoBehaviour
{
[Tooltip ("Time in seconds to fade in/out the loader.")]
public float fadeSpeed = 1f;
private CanvasGroup canvasGroup;
public void Show ()
{
Debug.Log ("[Loader] Show");
StopCoroutine ("Fade");
StartCoroutine (Fade (1, fadeSpeed));
}
public void Hide ()
{
Debug.Log ("[Loader] Hide");
StopCoroutine ("Fade");
StartCoroutine (Fade (0, fadeSpeed));
}
void Start ()
{
canvasGroup = GetComponent<CanvasGroup> ();
}
IEnumerator Fade (float alpha, float speed)
{
float speedForAlphaChange = (alpha - canvasGroup.alpha) / speed;
while (!Mathf.Approximately (canvasGroup.alpha, alpha)) {
canvasGroup.alpha += (speedForAlphaChange * Time.deltaTime);
yield return null;
}
}
}
```
Fix bug where loader fade would not stop | ```c#
using UnityEngine;
using System.Collections;
using System;
[RequireComponent (typeof(CanvasGroup))]
public class Loader : MonoBehaviour
{
[Tooltip ("Time in seconds to fade in/out the loader.")]
public float fadeSpeed = 1f;
private CanvasGroup canvasGroup;
private IEnumerator currentFade;
public void Show ()
{
Debug.Log ("[Loader] Show");
StopCurrentFade ();
currentFade = Fade (1, fadeSpeed);
StartCoroutine (currentFade);
}
public void Hide ()
{
Debug.Log ("[Loader] Hide");
StopCurrentFade ();
currentFade = Fade (0, fadeSpeed);
StartCoroutine (currentFade);
}
void Start ()
{
canvasGroup = GetComponent<CanvasGroup> ();
}
void StopCurrentFade ()
{
if (currentFade != null) {
StopCoroutine (currentFade);
}
}
IEnumerator Fade (float alpha, float speed)
{
float speedForAlphaChange = (alpha - canvasGroup.alpha) / speed;
while (!Mathf.Approximately (canvasGroup.alpha, alpha)) {
canvasGroup.alpha += (speedForAlphaChange * Time.deltaTime);
yield return null;
}
}
}
``` |
294cc12c-6c92-4059-a9d6-ee8f43fa663a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LanguageExt;
using static LanguageExt.Prelude;
namespace SolidworksAddinFramework
{
public static class BoolExtensions
{
public static Option<T> IfTrue<T>(this bool v, Func<T> fn) => v ? Some(fn()) : None;
public static Option<T> IfTrue<T>(this bool v, T t) => v.IfTrue(() => t);
}
}
```
Add IfTrue for fluent composition of bool | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LanguageExt;
using static LanguageExt.Prelude;
namespace SolidworksAddinFramework
{
public static class BoolExtensions
{
public static Option<T> IfTrue<T>(this bool v, Func<T> fn) => v ? Some(fn()) : None;
public static bool IfTrue(this bool v, Action fn)
{
if (v)
fn();
return true;
}
public static Option<T> IfTrue<T>(this bool v, T t) => v.IfTrue(() => t);
}
}
``` |
a2831026-c98d-4ec7-861b-9923b599e8dc | {
"language": "C#"
} | ```c#
using Rees.TangyFruitMapper.UnitTest.TestData;
using Xunit;
using Xunit.Abstractions;
namespace Rees.TangyFruitMapper.UnitTest
{
public class Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix : MappingGeneratorScenarios<DtoType4, ModelType4_UnderscoreBackingField>
{
public Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void Generate_ShouldOutputCode()
{
Assert.NotEmpty(this.GeneratedCode);
}
[Fact]
public void Generate_ShouldSuccessfullyMapToDto()
{
var mapper = CreateMapperFromGeneratedCode();
var result = mapper.ToDto(new ModelType4_UnderscoreBackingField(410, 3.1415M, "Pie Constant"));
Assert.Equal(410, result.Age);
Assert.Equal(3.1415M, result.MyNumber);
Assert.Equal("Pie Constant", result.Name);
}
[Fact]
public void Generate_ShouldSuccessfullyMapToModel()
{
// This is not supported. Properties must be writable at least with private setters.
Assert.True(this.GeneratedCode.Contains("// TODO No properties found to map"));
}
}
}
```
Correct the name of this test | ```c#
using Rees.TangyFruitMapper.UnitTest.TestData;
using Xunit;
using Xunit.Abstractions;
namespace Rees.TangyFruitMapper.UnitTest
{
public class Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix : MappingGeneratorScenarios<DtoType4, ModelType4_UnderscoreBackingField>
{
public Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void Generate_ShouldOutputCode()
{
Assert.NotEmpty(this.GeneratedCode);
}
[Fact]
public void Generate_ShouldSuccessfullyMapToDto()
{
var mapper = CreateMapperFromGeneratedCode();
var result = mapper.ToDto(new ModelType4_UnderscoreBackingField(410, 3.1415M, "Pie Constant"));
Assert.Equal(410, result.Age);
Assert.Equal(3.1415M, result.MyNumber);
Assert.Equal("Pie Constant", result.Name);
}
[Fact]
public void Generate_ShouldNOTMapToModel()
{
// This is not supported. Properties must be writable at least with private setters.
Assert.True(this.GeneratedCode.Contains("// TODO No properties found to map"));
}
}
}
``` |
95d8ebcb-cd19-4b2e-b23c-439243c0a4e7 | {
"language": "C#"
} | ```c#
@model Samaritans.Models.EventViewModel
@{
ViewBag.Title = Model.Name;
}
<h2>@Model.Name</h2>
```
Add view for displaying event details | ```c#
@model Samaritans.Models.EventViewModel
@{
ViewBag.Title = Model.Name;
}
<article class="event">
<form>
<h2>@M<input type="type" name="name" value="odel.Name</h2>
<div>@Model.EventTime</div>
<div>@Model.Attendance</div>
<p>@Model.Purpose</p>
<h3>Bring:</h3>
@for (var i = 0; i < Model.Resources.Length; i++)
{
var resources = Model.Resources[i];
<div>
<span>resource.Description</span>
<input type="hidden" name="resources[i].description" />
<input type="number" name="resources[i].quantity" />
</div>
}
" /> type="submit" value="Join" />
</form>
</article>
``` |
a192e3f4-1852-45c8-9135-454afbd3e84d | {
"language": "C#"
} | ```c#
using System;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse.Agent.Web
{
public class GlimpseAgentWebOptionsSetup : ConfigureOptions<GlimpseAgentWebOptions>
{
public GlimpseAgentWebOptionsSetup() : base(ConfigureGlimpseAgentWebOptions)
{
Order = -1000;
}
public static void ConfigureGlimpseAgentWebOptions(GlimpseAgentWebOptions options)
{
// Set up IgnoredUris
options.IgnoredUris.Add("__browserLink/requestData");
}
}
}```
Add more registrations for what uris should be ignored out of the box | ```c#
using System;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse.Agent.Web
{
public class GlimpseAgentWebOptionsSetup : ConfigureOptions<GlimpseAgentWebOptions>
{
public GlimpseAgentWebOptionsSetup() : base(ConfigureGlimpseAgentWebOptions)
{
Order = -1000;
}
public static void ConfigureGlimpseAgentWebOptions(GlimpseAgentWebOptions options)
{
// Set up IgnoredUris
options.IgnoredUris.Add("^__browserLink//requestData");
options.IgnoredUris.Add("^//Glimpse");
options.IgnoredUris.Add("^favicon.ico");
}
}
}``` |
77b19a59-5937-406f-8f64-7399eae5e133 | {
"language": "C#"
} | ```c#
using System;
using MySql.Data.MySqlClient;
namespace SideBySide
{
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
var csb = AppConfig.CreateConnectionStringBuilder();
var connectionString = csb.ConnectionString;
var database = csb.Database;
csb.Database = "";
using (var db = new MySqlConnection(csb.ConnectionString))
{
db.Open();
using (var cmd = db.CreateCommand())
{
cmd.CommandText = $"create schema if not exists {database};";
cmd.ExecuteNonQuery();
if (!string.IsNullOrEmpty(AppConfig.SecondaryDatabase))
{
cmd.CommandText = $"create schema if not exists {AppConfig.SecondaryDatabase};";
cmd.ExecuteNonQuery();
}
}
db.Close();
}
Connection = new MySqlConnection(connectionString);
}
public MySqlConnection Connection { get; }
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Connection.Dispose();
}
}
}
}
```
Increase thread pool min threads. | ```c#
using System;
#if NETCOREAPP1_1_2
using System.Reflection;
#endif
using System.Threading;
using MySql.Data.MySqlClient;
namespace SideBySide
{
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
// increase the number of worker threads to reduce number of spurious failures from threadpool starvation
#if NETCOREAPP1_1_2
// from https://stackoverflow.com/a/42982698
typeof(ThreadPool).GetMethod("SetMinThreads", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { 64, 64 });
#else
ThreadPool.SetMinThreads(64, 64);
#endif
var csb = AppConfig.CreateConnectionStringBuilder();
var connectionString = csb.ConnectionString;
var database = csb.Database;
csb.Database = "";
using (var db = new MySqlConnection(csb.ConnectionString))
{
db.Open();
using (var cmd = db.CreateCommand())
{
cmd.CommandText = $"create schema if not exists {database};";
cmd.ExecuteNonQuery();
if (!string.IsNullOrEmpty(AppConfig.SecondaryDatabase))
{
cmd.CommandText = $"create schema if not exists {AppConfig.SecondaryDatabase};";
cmd.ExecuteNonQuery();
}
}
db.Close();
}
Connection = new MySqlConnection(connectionString);
}
public MySqlConnection Connection { get; }
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Connection.Dispose();
}
}
}
}
``` |
bddc7f5d-8d24-407b-9182-73d122f76385 | {
"language": "C#"
} | ```c#
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.Psi;
namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.Analysis
{
public class CSharpHighlightingTestBase<T> : CSharpHighlightingTestBase
{
protected sealed override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile,
IContextBoundSettingsStore settingsStore)
{
return highlighting is T;
}
}
}```
Make test base class abstract | ```c#
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.Psi;
namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.Analysis
{
public abstract class CSharpHighlightingTestBase<T> : CSharpHighlightingTestBase
{
protected sealed override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile,
IContextBoundSettingsStore settingsStore)
{
return highlighting is T;
}
}
}``` |
9e47d880-699c-4537-8a64-aa7098fad562 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using TTreeDataModel;
namespace TTreeParser.Tests
{
public static class TUtils
{
/// <summary>
/// Find a class in the list, return null if we can't find it.
/// </summary>
/// <param name="classes"></param>
/// <param name="name"></param>
/// <returns></returns>
public static ROOTClassShell FindClass(this IEnumerable<ROOTClassShell> classes, string name)
{
return classes.Where(c => c.Name == name).FirstOrDefault();
}
/// <summary>
/// Find the class item for a particular item.
/// </summary>
/// <param name="cls"></param>
/// <param name="itemName"></param>
/// <returns></returns>
public static IClassItem FindItem(this ROOTClassShell cls, string itemName)
{
return cls.Items.Where(i => i.Name == itemName).FirstOrDefault();
}
}
}
```
Check for uniqueness for the classes that come back. | ```c#
using System.Collections.Generic;
using System.Linq;
using TTreeDataModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TTreeParser.Tests
{
public static class TUtils
{
/// <summary>
/// Find a class in the list, return null if we can't find it.
/// </summary>
/// <param name="classes"></param>
/// <param name="name"></param>
/// <returns></returns>
public static ROOTClassShell FindClass(this IEnumerable<ROOTClassShell> classes, string name)
{
Assert.AreEqual(1, classes.Where(c => c.Name == name).Count(), string.Format("# of classes called {0}", name));
return classes.Where(c => c.Name == name).FirstOrDefault();
}
/// <summary>
/// Find the class item for a particular item.
/// </summary>
/// <param name="cls"></param>
/// <param name="itemName"></param>
/// <returns></returns>
public static IClassItem FindItem(this ROOTClassShell cls, string itemName)
{
return cls.Items.Where(i => i.Name == itemName).FirstOrDefault();
}
}
}
``` |
b1e80693-5062-470b-b16a-ee697d86bc40 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using Newtonsoft.Json;
namespace Rackspace.CloudOffice
{
internal static class BodyEncoder
{
public static string Encode(object data, string contentType)
{
switch (contentType)
{
case ApiClient.ContentType.UrlEncoded: return FormUrlEncode(GetObjectAsDictionary(data));
case ApiClient.ContentType.Json: return JsonConvert.SerializeObject(data);
default: throw new ArgumentException("Unsupported contentType: " + contentType);
}
}
static string FormUrlEncode(IDictionary<string, string> data)
{
var pairs = data.Select(pair => string.Format("{0}={1}",
WebUtility.UrlEncode(pair.Key),
WebUtility.UrlEncode(pair.Value)));
return string.Join("&", pairs);
}
static IDictionary<string, string> GetObjectAsDictionary(object obj)
{
var dict = new Dictionary<string, string>();
var properties = obj.GetType()
.GetMembers(BindingFlags.Public | BindingFlags.Instance)
.OfType<PropertyInfo>();
foreach (var prop in properties)
dict[prop.Name] = Convert.ToString(prop.GetValue(obj));
return dict;
}
}
}
```
Support sending an empty body | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using Newtonsoft.Json;
namespace Rackspace.CloudOffice
{
internal static class BodyEncoder
{
public static string Encode(object data, string contentType)
{
if (data == null)
return string.Empty;
switch (contentType)
{
case ApiClient.ContentType.UrlEncoded: return FormUrlEncode(GetObjectAsDictionary(data));
case ApiClient.ContentType.Json: return JsonConvert.SerializeObject(data);
default: throw new ArgumentException("Unsupported contentType: " + contentType);
}
}
static string FormUrlEncode(IDictionary<string, string> data)
{
var pairs = data.Select(pair => string.Format("{0}={1}",
WebUtility.UrlEncode(pair.Key),
WebUtility.UrlEncode(pair.Value)));
return string.Join("&", pairs);
}
static IDictionary<string, string> GetObjectAsDictionary(object obj)
{
var dict = new Dictionary<string, string>();
var properties = obj.GetType()
.GetMembers(BindingFlags.Public | BindingFlags.Instance)
.OfType<PropertyInfo>();
foreach (var prop in properties)
dict[prop.Name] = Convert.ToString(prop.GetValue(obj));
return dict;
}
}
}
``` |
218d664f-0aa7-411c-893d-ab0df41f2fa2 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Wukong.Models;
namespace Wukong.Controllers
{
[Route("oauth")]
public class AuthController : Controller
{
[HttpGet("all")]
public IEnumerable<OAuthMethod> AllSchemes()
{
return
new List<OAuthMethod>{ new OAuthMethod()
{
Scheme = "Microsoft",
DisplayName = "Microsoft",
Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}"
}};
}
[HttpGet("go/{any}")]
public async Task SignIn(string any, string redirectUri = "/")
{
await HttpContext.ChallengeAsync(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties {
RedirectUri = redirectUri,
IsPersistent = true,
ExpiresUtc = System.DateTime.UtcNow.AddDays(30)
});
}
[HttpGet("signout")]
public SignOutResult SignOut(string redirectUrl = "/")
{
return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
}```
Revert "Make cookie valid for 30 days." | ```c#
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Wukong.Models;
namespace Wukong.Controllers
{
[Route("oauth")]
public class AuthController : Controller
{
[HttpGet("all")]
public IEnumerable<OAuthMethod> AllSchemes()
{
return
new List<OAuthMethod>{ new OAuthMethod()
{
Scheme = "Microsoft",
DisplayName = "Microsoft",
Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}"
}};
}
[HttpGet("go/{any}")]
public async Task SignIn(string any, string redirectUri = "/")
{
await HttpContext.ChallengeAsync(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties {
RedirectUri = redirectUri,
IsPersistent = true
});
}
[HttpGet("signout")]
public SignOutResult SignOut(string redirectUrl = "/")
{
return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
}``` |
9fee71eb-17b0-43ab-bbab-a1d53dba1ad7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace EchoNestNET
{
[JsonObject]
public class Genre
{
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "description")]
public string description { get; set; }
[JsonProperty(PropertyName = "similarity")]
public float similarity { get; set; }
[JsonObject]
public class Urls
{
[JsonProperty(PropertyName = "wikipedia_url")]
public string wikipediaUrl { get; set; }
}
}
}
```
Remove ConsoleApplication used for quick testing | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace EchoNestNET
{
[JsonObject]
public class Genre
{
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "description")]
public string description { get; set; }
[JsonProperty(PropertyName = "similarity")]
public float similarity { get; set; }
[JsonObject]
public class Urls
{
[JsonProperty(PropertyName = "wikipedia_url")]
public string wikipediaUrl { get; set; }
}
}
}
``` |
b5955e56-fdb5-436e-a558-9a70a7189a17 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using MediatR;
using SFA.DAS.EmployerApprenticeshipsService.Application.Queries.GetEmployerAccount;
using SFA.DAS.EmployerApprenticeshipsService.Application.Queries.GetEmployerAccountTransactions;
using SFA.DAS.EmployerApprenticeshipsService.Domain;
namespace SFA.DAS.EmployerApprenticeshipsService.Web.Orchestrators
{
public class EmployerAccountTransactionsOrchestrator
{
private readonly IMediator _mediator;
public EmployerAccountTransactionsOrchestrator(IMediator mediator)
{
if (mediator == null)
throw new ArgumentNullException(nameof(mediator));
_mediator = mediator;
}
public async Task<TransactionViewResult> GetAccountTransactions(int accountId)
{
var employerAccountResult = await _mediator.SendAsync(new GetEmployerAccountQuery { Id = accountId });
if (employerAccountResult == null)
{
return new TransactionViewResult();
}
var data = await _mediator.SendAsync(new GetEmployerAccountTransactionsQuery {AccountId = accountId});
return new TransactionViewResult
{
Account = null,
Model = new TransactionViewModel
{
Data = data.Data
}
};
}
}
public class TransactionViewResult
{
public Account Account { get; set; }
public TransactionViewModel Model { get; set; }
}
public class TransactionViewModel
{
public AggregationData Data { get; set; }
}
}```
Send Account model back for validation | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using MediatR;
using SFA.DAS.EmployerApprenticeshipsService.Application.Queries.GetEmployerAccount;
using SFA.DAS.EmployerApprenticeshipsService.Application.Queries.GetEmployerAccountTransactions;
using SFA.DAS.EmployerApprenticeshipsService.Domain;
namespace SFA.DAS.EmployerApprenticeshipsService.Web.Orchestrators
{
public class EmployerAccountTransactionsOrchestrator
{
private readonly IMediator _mediator;
public EmployerAccountTransactionsOrchestrator(IMediator mediator)
{
if (mediator == null)
throw new ArgumentNullException(nameof(mediator));
_mediator = mediator;
}
public async Task<TransactionViewResult> GetAccountTransactions(int accountId)
{
var employerAccountResult = await _mediator.SendAsync(new GetEmployerAccountQuery { Id = accountId });
if (employerAccountResult == null)
{
return new TransactionViewResult();
}
var data = await _mediator.SendAsync(new GetEmployerAccountTransactionsQuery {AccountId = accountId});
return new TransactionViewResult
{
Account = employerAccountResult.Account,
Model = new TransactionViewModel
{
Data = data.Data
}
};
}
}
public class TransactionViewResult
{
public Account Account { get; set; }
public TransactionViewModel Model { get; set; }
}
public class TransactionViewModel
{
public AggregationData Data { get; set; }
}
}``` |
9be25b46-dd22-49e6-b43a-c721fbfa66ad | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osuTK;
namespace osu.Framework.Input.Handlers.Tablet
{
/// <summary>
/// An interface to access OpenTabletDriverHandler.
/// Can be considered for removal when we no longer require dual targeting against netstandard.
/// </summary>
public interface ITabletHandler
{
/// <summary>
/// The offset of the area which should be mapped to the game window.
/// </summary>
Bindable<Vector2> AreaOffset { get; }
/// <summary>
/// The size of the area which should be mapped to the game window.
/// </summary>
Bindable<Vector2> AreaSize { get; }
/// <summary>
/// Information on the currently connected tablet device./ May be null if no tablet is detected.
/// </summary>
IBindable<TabletInfo> Tablet { get; }
BindableBool Enabled { get; }
}
}
```
Fix stray character in xmldoc | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osuTK;
namespace osu.Framework.Input.Handlers.Tablet
{
/// <summary>
/// An interface to access OpenTabletDriverHandler.
/// Can be considered for removal when we no longer require dual targeting against netstandard.
/// </summary>
public interface ITabletHandler
{
/// <summary>
/// The offset of the area which should be mapped to the game window.
/// </summary>
Bindable<Vector2> AreaOffset { get; }
/// <summary>
/// The size of the area which should be mapped to the game window.
/// </summary>
Bindable<Vector2> AreaSize { get; }
/// <summary>
/// Information on the currently connected tablet device. May be null if no tablet is detected.
/// </summary>
IBindable<TabletInfo> Tablet { get; }
BindableBool Enabled { get; }
}
}
``` |
476c8f3b-51d9-4a02-a705-baaf0c3a5ff9 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Reflection;
using GraphQL.Types;
namespace GraphQL.Resolvers
{
public class MethodModelBinderResolver<T> : IFieldResolver
{
private readonly IDependencyResolver _dependencyResolver;
private readonly MethodInfo _methodInfo;
private readonly ParameterInfo[] _parameters;
private readonly Type _type;
public MethodModelBinderResolver(MethodInfo methodInfo, IDependencyResolver dependencyResolver)
{
_dependencyResolver = dependencyResolver;
_type = typeof(T);
_methodInfo = methodInfo;
_parameters = _methodInfo.GetParameters();
}
public object Resolve(ResolveFieldContext context)
{
var index = 0;
var arguments = new object[_parameters.Length];
if (_parameters.Any() && typeof(ResolveFieldContext) == _parameters[index].ParameterType)
{
arguments[index] = context;
index++;
}
if (_parameters.Any() && context.Source?.GetType() == _parameters[index].ParameterType)
{
arguments[index] = context.Source;
index++;
}
foreach (var parameter in _parameters.Skip(index))
{
arguments[index] = context.GetArgument(parameter.Name, parameter.ParameterType);
index++;
}
var target = _dependencyResolver.Resolve(_type);
if (target == null)
{
throw new InvalidOperationException($"Could not resolve an instance of {_type.Name} to execute {context.FieldName}");
}
return _methodInfo.Invoke(target, arguments);
}
}
}
```
Refactor how parameters are checked | ```c#
using System;
using System.Linq;
using System.Reflection;
using GraphQL.Types;
namespace GraphQL.Resolvers
{
public class MethodModelBinderResolver<T> : IFieldResolver
{
private readonly IDependencyResolver _dependencyResolver;
private readonly MethodInfo _methodInfo;
private readonly ParameterInfo[] _parameters;
private readonly Type _type;
public MethodModelBinderResolver(MethodInfo methodInfo, IDependencyResolver dependencyResolver)
{
_dependencyResolver = dependencyResolver;
_type = typeof(T);
_methodInfo = methodInfo;
_parameters = _methodInfo.GetParameters();
}
public object Resolve(ResolveFieldContext context)
{
object[] arguments = null;
if (_parameters.Any())
{
arguments = new object[_parameters.Length];
var index = 0;
if (typeof(ResolveFieldContext) == _parameters[index].ParameterType)
{
arguments[index] = context;
index++;
}
if (context.Source?.GetType() == _parameters[index].ParameterType)
{
arguments[index] = context.Source;
index++;
}
foreach (var parameter in _parameters.Skip(index))
{
arguments[index] = context.GetArgument(parameter.Name, parameter.ParameterType);
index++;
}
}
var target = _dependencyResolver.Resolve(_type);
if (target == null)
{
var parentType = context.ParentType != null ? $"{context.ParentType.Name}." : null;
throw new InvalidOperationException($"Could not resolve an instance of {_type.Name} to execute {parentType}{context.FieldName}");
}
return _methodInfo.Invoke(target, arguments);
}
}
}
``` |
80e80c73-86ac-426d-90cd-5f67dc4c1d6e | {
"language": "C#"
} | ```c#
using MultiMiner.Utility.Serialization;
using System.Linq;
namespace MultiMiner.Win.Extensions
{
public static class ApplicationConfigurationExtensions
{
public static Remoting.Data.Transfer.Configuration.Application ToTransferObject(this Data.Configuration.Application modelObject)
{
Remoting.Data.Transfer.Configuration.Application transferObject = new Remoting.Data.Transfer.Configuration.Application();
ObjectCopier.CopyObject(modelObject, transferObject, "HiddenColumns");
transferObject.HiddenColumns = modelObject.HiddenColumns.ToArray();
return transferObject;
}
public static Data.Configuration.Application ToModelObject(this Remoting.Data.Transfer.Configuration.Application transferObject)
{
Data.Configuration.Application modelObject = new Data.Configuration.Application();
ObjectCopier.CopyObject(transferObject, modelObject, "HiddenColumns");
modelObject.HiddenColumns = transferObject.HiddenColumns.ToList();
return modelObject;
}
}
}
```
Fix ArgumentNullException configuring pools via Remoting | ```c#
using MultiMiner.Utility.Serialization;
using System.Linq;
namespace MultiMiner.Win.Extensions
{
public static class ApplicationConfigurationExtensions
{
public static Remoting.Data.Transfer.Configuration.Application ToTransferObject(this Data.Configuration.Application modelObject)
{
Remoting.Data.Transfer.Configuration.Application transferObject = new Remoting.Data.Transfer.Configuration.Application();
ObjectCopier.CopyObject(modelObject, transferObject, "HiddenColumns");
if (modelObject.HiddenColumns != null)
transferObject.HiddenColumns = modelObject.HiddenColumns.ToArray();
return transferObject;
}
public static Data.Configuration.Application ToModelObject(this Remoting.Data.Transfer.Configuration.Application transferObject)
{
Data.Configuration.Application modelObject = new Data.Configuration.Application();
ObjectCopier.CopyObject(transferObject, modelObject, "HiddenColumns");
if (transferObject.HiddenColumns != null)
modelObject.HiddenColumns = transferObject.HiddenColumns.ToList();
return modelObject;
}
}
}
``` |
62a27efd-5526-4bd3-947b-0eadd5f50aeb | {
"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("TeamMaker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TeamMaker")]
[assembly: AssemblyCopyright("Copyright © 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("71703720-56ba-4e6a-9004-239a9836693b")]
// 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")]
```
Increment version number in assembly info | ```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("TeamMaker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TeamMaker")]
[assembly: AssemblyCopyright("Copyright © 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("71703720-56ba-4e6a-9004-239a9836693b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2")]
[assembly: AssemblyFileVersion("1.0.2")]
``` |
29925d5f-5dbc-4385-a8c7-fd03cd907884 | {
"language": "C#"
} | ```c#
using BugsnagUnity.Payload;
namespace BugsnagUnity
{
public interface ISessionTracker
{
void StartSession();
Session CurrentSession { get; }
}
class SessionTracker : ISessionTracker
{
private IClient Client { get; }
private Session _currentSession;
public Session CurrentSession
{
get => _currentSession.Copy();
private set => _currentSession = value;
}
internal SessionTracker(IClient client)
{
Client = client;
}
public void StartSession()
{
var session = new Session();
CurrentSession = session;
var payload = new SessionReport(Client.Configuration, Client.User, session);
Client.Send(payload);
}
}
}
```
Handle not having a current session | ```c#
using BugsnagUnity.Payload;
namespace BugsnagUnity
{
public interface ISessionTracker
{
void StartSession();
Session CurrentSession { get; }
}
class SessionTracker : ISessionTracker
{
private IClient Client { get; }
private Session _currentSession;
public Session CurrentSession
{
get => _currentSession?.Copy();
private set => _currentSession = value;
}
internal SessionTracker(IClient client)
{
Client = client;
}
public void StartSession()
{
var session = new Session();
CurrentSession = session;
var payload = new SessionReport(Client.Configuration, Client.User, session);
Client.Send(payload);
}
}
}
``` |
6b7aa33f-75e6-4552-bae6-74be871b55f6 | {
"language": "C#"
} | ```c#
namespace ACE.Network.GameEvent
{
public class GameEventCharacterTitle : GameEventPacket
{
public override GameEventOpcode Opcode { get { return GameEventOpcode.CharacterTitle; } }
public GameEventCharacterTitle(Session session) : base(session) { }
protected override void WriteEventBody()
{
fragment.Payload.Write(1u);
fragment.Payload.Write(1u); // TODO: get current title from database
fragment.Payload.Write(1000u); // TODO: get player's title list from database
for (uint i = 1; i <= 1000; i++)
fragment.Payload.Write(i);
}
}
}
```
Reduce temporary list of titles | ```c#
namespace ACE.Network.GameEvent
{
public class GameEventCharacterTitle : GameEventPacket
{
public override GameEventOpcode Opcode { get { return GameEventOpcode.CharacterTitle; } }
public GameEventCharacterTitle(Session session) : base(session) { }
protected override void WriteEventBody()
{
fragment.Payload.Write(1u);
fragment.Payload.Write(1u); // TODO: get current title from database
fragment.Payload.Write(10u); // TODO: get player's title list from database
for (uint i = 1; i <= 10; i++)
fragment.Payload.Write(i);
}
}
}
``` |
48422d0d-3012-448b-9fa4-9bb4667e142a | {
"language": "C#"
} | ```c#
using System;
using System.Web.Http;
using Agiil.Bootstrap.DiConfiguration;
using Autofac;
namespace Agiil.Web.App_Start
{
public static class ContainerFactoryProviderExtensions
{
public static IContainer GetContainer(this ContainerFactoryProvider provider, HttpConfiguration config)
{
if(provider == null)
throw new ArgumentNullException(nameof(provider));
if(config == null)
throw new ArgumentNullException(nameof(config));
var factoryProvider = new ContainerFactoryProvider();
var diFactory = factoryProvider.GetContainerBuilderFactory() as IContainerFactoryWithHttpConfiguration;
if(diFactory == null)
throw new InvalidOperationException($"The configured container builder factory must implement {nameof(IContainerFactoryWithHttpConfiguration)}.");
diFactory.SetHttpConfiguration(config);
return diFactory.GetContainer();
}
}
}
```
Fix silly mistake in DI configuration | ```c#
using System;
using System.Web.Http;
using Agiil.Bootstrap.DiConfiguration;
using Autofac;
namespace Agiil.Web.App_Start
{
public static class ContainerFactoryProviderExtensions
{
public static IContainer GetContainer(this ContainerFactoryProvider provider, HttpConfiguration config)
{
if(provider == null)
throw new ArgumentNullException(nameof(provider));
if(config == null)
throw new ArgumentNullException(nameof(config));
var diFactory = provider.GetContainerBuilderFactory() as IContainerFactoryWithHttpConfiguration;
if(diFactory == null)
throw new InvalidOperationException($"The configured container builder factory must implement {nameof(IContainerFactoryWithHttpConfiguration)}.");
diFactory.SetHttpConfiguration(config);
return diFactory.GetContainer();
}
}
}
``` |
33e51f36-df03-4ac5-83a2-71f98f878366 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using AgateLib.Extensions.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AgateLib.UnitTests.Extensions
{
[TestClass]
public class ListExtensions
{
[TestMethod]
public void SortPrimitives()
{
List<int> li = new List<int> { 1, 6, 2, 3, 8, 10, 9, 7, 4, 5 };
Assert.AreEqual(10, li.Count);
li.InsertionSort();
for (int i = 0; i < li.Count; i++)
Assert.AreEqual(i + 1, li[i]);
}
}
}
```
Move to modern nuget. Make Sprite compile by stubbing missing interface methods. | ```c#
using System.Collections.Generic;
using AgateLib.Extensions.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AgateLib.UnitTests.Extensions
{
[TestClass]
public class ListExtensions
{
[TestMethod]
public void SortPrimitives()
{
List<int> li = new List<int> { 1, 6, 2, 3, 8, 10, 9, 7, 4, 5 };
Assert.AreEqual(10, li.Count);
li.InsertionSort();
for (int i = 0; i < li.Count; i++)
Assert.AreEqual(i + 1, li[i]);
}
[TestMethod]
public void InsertionSortTest()
{
List<int> list = new List<int> { 4, 2, 3, 1, 6, 7, 8, 9 };
list.InsertionSort();
Assert.AreEqual(1, list[0]);
Assert.AreEqual(9, list[list.Count - 1]);
}
}
}
``` |
e315c85a-cf44-48c6-a99b-802c48641a58 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using HelloCoreClrApp.Data;
using HelloCoreClrApp.WebApi.Messages;
using Serilog;
namespace HelloCoreClrApp.WebApi.Actions
{
public class SayHelloWorldAction : ISayHelloWorldAction
{
private static readonly ILogger Log = Serilog.Log.ForContext<SayHelloWorldAction>();
private readonly IDataService dataService;
public SayHelloWorldAction(IDataService dataService)
{
this.dataService = dataService;
}
public async Task<SayHelloWorldResponse> Execute(string name)
{
Log.Information("Calculating result.");
Tuple<string, bool> res = Rules.SayHelloWorldRule.Process(name);
if (res.Item2)
await SaveGreeting(res.Item1);
return new SayHelloWorldResponse { Greeting = res.Item1 };
}
private async Task SaveGreeting(string greeting)
{
Log.Information("Save greeting.");
await dataService.SaveGreeting(greeting);
}
}
}
```
Use var. Rider finally understands it here ;) | ```c#
using System.Threading.Tasks;
using HelloCoreClrApp.Data;
using HelloCoreClrApp.WebApi.Messages;
using Serilog;
namespace HelloCoreClrApp.WebApi.Actions
{
public class SayHelloWorldAction : ISayHelloWorldAction
{
private static readonly ILogger Log = Serilog.Log.ForContext<SayHelloWorldAction>();
private readonly IDataService dataService;
public SayHelloWorldAction(IDataService dataService)
{
this.dataService = dataService;
}
public async Task<SayHelloWorldResponse> Execute(string name)
{
Log.Information("Calculating result.");
var res = Rules.SayHelloWorldRule.Process(name);
if (res.Item2)
await SaveGreeting(res.Item1);
return new SayHelloWorldResponse { Greeting = res.Item1 };
}
private async Task SaveGreeting(string greeting)
{
Log.Information("Save greeting.");
await dataService.SaveGreeting(greeting);
}
}
}
``` |
5b516fb5-3da2-484d-9424-3c9d81397eb8 | {
"language": "C#"
} | ```c#
#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Restore-NuGet-Packages")
.Does(() =>
{
NuGetRestore("SimpSim.NET.sln");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
MSBuild("SimpSim.NET.sln", settings => settings.SetConfiguration(configuration));
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
NUnit3("./**/bin/" + configuration + "/*.Tests.dll", new NUnit3Settings { NoResults = true });
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
```
Fix Cake script not running tests from SimpSim.NET.Tests project. | ```c#
#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Restore-NuGet-Packages")
.Does(() =>
{
NuGetRestore("SimpSim.NET.sln");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
MSBuild("SimpSim.NET.sln", settings => settings.SetConfiguration(configuration));
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./SimpSim.NET.Tests/SimpSim.NET.Tests.csproj");
NUnit3("./**/bin/" + configuration + "/SimpSim.NET.Presentation.Tests.dll", new NUnit3Settings { NoResults = true });
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
``` |
45dd4f5d-8320-442b-92a0-f32838e32791 | {
"language": "C#"
} | ```c#
@functions {
private string GetCssClass(string actionName, string controllerName)
{
var currentControllerName = ViewContext.RouteData.Values["controller"].ToString();
var isCurrentController = currentControllerName == controllerName;
if (currentControllerName == "Home")
{
return GetHomeControllerLinksCssClass(actionName, isCurrentController);
}
return isCurrentController ? "active" : string.Empty;
}
private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController)
{
if (!isCurrentController)
{
return string.Empty;
}
var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName;
return isCurrentAction ? "active" : string.Empty;
}
}
@helper GetMenuBarLink(string linkText, string actionName, string controllerName)
{
<li class="@GetCssClass(actionName, controllerName)">@Html.ActionLink(linkText, actionName, controllerName)</li>
}
<ul class="nav">
@GetMenuBarLink("Home", "Index", "Home")
@GetMenuBarLink("Concerts", "Index", "Concerts")
@GetMenuBarLink("Rehearsals", "Index", "Rehearsals")
@GetMenuBarLink("About", "About", "Home")
@GetMenuBarLink("Contact", "Contact", "Home")
</ul>
```
Add drop-down menu for concerts. | ```c#
@functions {
private string GetCssClass(string actionName, string controllerName)
{
var currentControllerName = ViewContext.RouteData.Values["controller"].ToString();
var isCurrentController = currentControllerName == controllerName;
if (currentControllerName == "Home")
{
return GetHomeControllerLinksCssClass(actionName, isCurrentController);
}
return isCurrentController ? "active" : string.Empty;
}
private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController)
{
if (!isCurrentController)
{
return string.Empty;
}
var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName;
return isCurrentAction ? "active" : string.Empty;
}
}
@helper GetMenuBarLink(string linkText, string actionName, string controllerName)
{
<li class="dropdown @GetCssClass(actionName, controllerName)">
@if (controllerName == "Concerts" && Request.IsAuthenticated)
{
<a href="@Url.Action(actionName, controllerName)" class="dropdown-toggle" data-toggle="dropdown">
@linkText
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Administer Concerts", "List", "Concerts")</li>
</ul>
}
else
{
@Html.ActionLink(linkText, actionName, controllerName)
}
</li>
}
<ul class="nav">
@GetMenuBarLink("Home", "Index", "Home")
@GetMenuBarLink("Concerts", "Index", "Concerts")
@GetMenuBarLink("Rehearsals", "Index", "Rehearsals")
@GetMenuBarLink("About", "About", "Home")
@GetMenuBarLink("Contact", "Contact", "Home")
</ul>
``` |
b1172701-b700-4057-8c31-6bae12f3ece7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Represents an email notification sent a user, employee, or administrator
/// </summary>
public class EmailNotification : Notification
{
public static String QueueName { get { return "EmailNotifications"; } }
/// <summary>
/// Who the email notification should be FROM
/// </summary>
public String FromAddress { get; set; }
/// <summary>
/// A list of email addresses to CC
/// </summary>
public ICollection<String> CC { get; set; } = new List<String>();
/// <summary>
/// A list of email addresses to BCC
/// </summary>
public ICollection<String> BCC { get; set; } = new List<String>();
/// <summary>
/// The subject line of the email
/// </summary>
public String Subject { get; set; }
/// <summary>
/// Any attachments to the email in the form of URLs to download
/// </summary>
public ICollection<Attachment> Attachments { get; set; } = new List<Attachment>();
/// <summary>
/// A file may be attached to the email notification by providing a URL to download
/// the file (will be downloaded by the sending process) and a filename
/// </summary>
public class Attachment
{
public String Filename { get; set; }
public String Uri { get; set; }
}
}
}```
Add the content type for notification attachments | ```c#
using System;
using System.Collections.Generic;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Represents an email notification sent a user, employee, or administrator
/// </summary>
public class EmailNotification : Notification
{
public static String QueueName { get { return "EmailNotifications"; } }
/// <summary>
/// Who the email notification should be FROM
/// </summary>
public String FromAddress { get; set; }
/// <summary>
/// A list of email addresses to CC
/// </summary>
public ICollection<String> CC { get; set; } = new List<String>();
/// <summary>
/// A list of email addresses to BCC
/// </summary>
public ICollection<String> BCC { get; set; } = new List<String>();
/// <summary>
/// The subject line of the email
/// </summary>
public String Subject { get; set; }
/// <summary>
/// Any attachments to the email in the form of URLs to download
/// </summary>
public ICollection<Attachment> Attachments { get; set; } = new List<Attachment>();
/// <summary>
/// A file may be attached to the email notification
/// </summary>
public class Attachment
{
/// <summary>
/// The filename of the attachment
/// </summary>
public String Filename { get; set; }
/// <summary>
/// If provided, the Base64 encoded content of the attachment
/// </summary>
public String Content { get; set; }
/// <summary>
/// If provided, an addressable URI from which the service can download the attachment
/// </summary>
public String Uri { get; set; }
}
}
}``` |
0d887d57-851b-4cc6-90c5-d267fbbb1d80 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Nimrod
{
public static class AssemblyLocator
{
static ConcurrentDictionary<string, Assembly> assemblies = new ConcurrentDictionary<string, Assembly>();
public static void Init()
{
AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly assembly;
assemblies.TryGetValue(args.Name, out assembly);
return assembly;
}
static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
Assembly assembly = args.LoadedAssembly;
assemblies[assembly.FullName] = assembly;
}
}
}
```
Return any assembly that match the name, do not look at version | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Nimrod
{
public static class AssemblyLocator
{
static ConcurrentDictionary<string, Assembly> assemblies = new ConcurrentDictionary<string, Assembly>();
public static void Init()
{
AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var assemblyName = new AssemblyName(args.Name);
Assembly assembly;
assemblies.TryGetValue(assemblyName.Name, out assembly);
// an assembly has been requested somewhere, but we don't load it
Debug.Assert(assembly != null);
return assembly;
}
static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
var assembly = args.LoadedAssembly;
var assemblyName = assembly.GetName();
// Note that we load assembly by name, not full name
// This means that we forgot the version number
// we should handle the version number too,
// but take into account that we want to deliver the assembly if we don't find the exact same version number
assemblies.TryAdd(assemblyName.Name, assembly);
}
}
}
``` |
c6c5be1b-6b76-440a-a864-a0d701a81e46 | {
"language": "C#"
} | ```c#
using System.Net;
using System.Configuration;
private static TraceWriter logger;
private static string[] LoadTopics()
{
string TopicsAndExperts = ConfigurationManager.AppSettings["EXPERTS_LIST"].ToString();
logger.Info($"Got TopicsAndExperts: {TopicsAndExperts}");
// split each topic and expert pair
string[] ExpertList = TopicsAndExperts.Split(';');
// Create container to return
List<string> Topics = new List<string>();
foreach (var item in ExpertList)
{
// split topic from expert
string[] TopicDetails = item.Split(',');
// load topic
Topics.Add(TopicDetails[0]);
logger.Info($"Loaded topic: {TopicDetails[0]}");
}
return Topics.ToArray();
}
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
// save the logging context for later use
logger = log;
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
string[] Topics = LoadTopics();
return Topics == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, Topics);
}```
Add a comment about the approach to loading topics | ```c#
using System.Net;
using System.Configuration;
private static TraceWriter logger;
/// Extract the topics from the and topics and experts list so there is one master list
/// and topics and experts stay in sync.
private static string[] LoadTopics()
{
string TopicsAndExperts = ConfigurationManager.AppSettings["EXPERTS_LIST"].ToString();
logger.Info($"Got TopicsAndExperts: {TopicsAndExperts}");
// split each topic and expert pair
string[] ExpertList = TopicsAndExperts.Split(';');
// Create container to return
List<string> Topics = new List<string>();
foreach (var item in ExpertList)
{
// split topic from expert
string[] TopicDetails = item.Split(',');
// load topic
Topics.Add(TopicDetails[0]);
logger.Info($"Loaded topic: {TopicDetails[0]}");
}
return Topics.ToArray();
}
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
// save the logging context for later use
logger = log;
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
string[] Topics = LoadTopics();
return Topics == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, Topics);
}``` |
74f20ae2-862a-431f-81b4-41fc37843232 | {
"language": "C#"
} | ```c#
using System;
using Xunit;
namespace PagedList.Tests
{
public class PageMetadataTests
{
[Fact]
public void PageNumberIsZero_ArgumentOutOfRangeExceptionIsThrown()
{
Assert.True(false);
// Assert.Throws<ArgumentOutOfRangeException>(() => new PageMetadata(10, 0, 1));
}
[Fact]
public void PageSizeIsZero_ArgumentOutOfRangeExceptionIsThrown()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PageMetadata(10, 1, 0));
}
}
}```
Revert "Testing to see if the deploy is started when a test fails" | ```c#
using System;
using Xunit;
namespace PagedList.Tests
{
public class PageMetadataTests
{
[Fact]
public void PageNumberIsZero_ArgumentOutOfRangeExceptionIsThrown()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PageMetadata(10, 0, 1));
}
[Fact]
public void PageSizeIsZero_ArgumentOutOfRangeExceptionIsThrown()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PageMetadata(10, 1, 0));
}
}
}``` |
aacac112-170f-44da-99f7-f6a8ec2bf00c | {
"language": "C#"
} | ```c#
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo
{
using System;
using Xunit;
public static class HashCodeHelpersFacts
{
[Fact]
public static void Combine2_DoesNotThrow_WhenOverflowed()
=> HashCodeHelpers.Combine(Int32.MaxValue, 1);
[Fact]
public static void Combine3_DoesNotThrow_WhenOverflowed()
=> HashCodeHelpers.Combine(Int32.MaxValue, 1, 1);
}
}
```
Add test for overflowed by min. | ```c#
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo
{
using System;
using Xunit;
public static class HashCodeHelpersFacts
{
[Fact]
public static void Combine2_DoesNotThrow_WhenMinOverflowed()
=> HashCodeHelpers.Combine(Int32.MinValue, 1);
[Fact]
public static void Combine2_DoesNotThrow_WhenMaxOverflowed()
=> HashCodeHelpers.Combine(Int32.MaxValue, 1);
[Fact]
public static void Combine3_DoesNotThrow_WhenMinOverflowed()
=> HashCodeHelpers.Combine(Int32.MinValue, 1, 1);
[Fact]
public static void Combine3_DoesNotThrow_WhenMaxOverflowed()
=> HashCodeHelpers.Combine(Int32.MaxValue, 1, 1);
}
}
``` |
d34a8b76-d329-439a-8882-bee059fe81eb | {
"language": "C#"
} | ```c#
// Server.cs
// <copyright file="Server.cs"> This code is protected under the MIT License. </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Networking
{
/// <summary>
/// A class that acts as a server for a networked game of tron.
/// </summary>
public class Server
{
/// <summary>
/// The port used by the server.
/// </summary>
public static readonly int Port = 22528;
}
}
```
Write properties and constructor for server | ```c#
// Server.cs
// <copyright file="Server.cs"> This code is protected under the MIT License. </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Networking
{
/// <summary>
/// A class that acts as a server for a networked game of tron.
/// </summary>
public class Server
{
/// <summary>
/// The port used by the server.
/// </summary>
public static readonly int Port = 22528;
public Server()
{
this.Host = new UdpClient(new IPEndPoint(IPAddress.Any, Server.Port));
this.PlayerIPs = new IPEndPoint[12];
}
/// <summary>
/// The host socket.
/// </summary>
public UdpClient Host { get; set; }
/// <summary>
/// The array of player ip addresses.
/// </summary>
public IPEndPoint[] PlayerIPs { get; set; }
/// <summary>
/// Listens for an input.
/// </summary>
public void Listen
{
}
/// <summary>
/// Sends a message to all clients.
/// </summary>
public void SendToAll()
{
}
/// <summary>
/// Removes a player from the game.
/// </summary>
public void RemovePlayer
{
}
}
}
``` |
b70ecf93-233c-456f-aeda-4bcb856c6b2b | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Database;
using osu.Game.Tests.Resources;
namespace osu.Game.Tests.Visual.Navigation
{
public class TestSceneStartupImport : OsuGameTestScene
{
private string importFilename;
protected override TestOsuGame CreateTestGame() => new TestOsuGame(LocalStorage, API, new[] { importFilename });
public override void SetUpSteps()
{
AddStep("Prepare import beatmap", () => importFilename = TestResources.GetTestBeatmapForImport());
base.SetUpSteps();
}
[Test]
public void TestImportCreatedNotification()
{
AddUntilStep("Import notification was presented", () => Game.Notifications.ChildrenOfType<ImportProgressNotification>().Count() == 1);
}
}
}
```
Fix startup import test waiting on potentially incorrect notification type | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Overlays.Notifications;
using osu.Game.Tests.Resources;
namespace osu.Game.Tests.Visual.Navigation
{
public class TestSceneStartupImport : OsuGameTestScene
{
private string importFilename;
protected override TestOsuGame CreateTestGame() => new TestOsuGame(LocalStorage, API, new[] { importFilename });
public override void SetUpSteps()
{
AddStep("Prepare import beatmap", () => importFilename = TestResources.GetTestBeatmapForImport());
base.SetUpSteps();
}
[Test]
public void TestImportCreatedNotification()
{
AddUntilStep("Import notification was presented", () => Game.Notifications.ChildrenOfType<ProgressCompletionNotification>().Count() == 1);
}
}
}
``` |
ca7859d0-b00f-4435-b458-e24ecf7d0d08 | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestReadModelDatabase.cs">
// Copyright (c) 2015. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Spritely.ReadModel.Sql.Test
{
using System;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using Spritely.Test.FluentMigratorSqlDatabase;
public class TestReadModelDatabase : ReadModelDatabase<TestReadModelDatabase>, IDisposable
{
public TestReadModelDatabase()
{
this.TestDatabase = new TestDatabase("Create_creates_runner_capable_of_populating_database.mdf");
this.TestDatabase.Create();
// Use TestMigration class in this assembly
var runner = FluentMigratorRunnerFactory.Create(Assembly.GetExecutingAssembly(), this.TestDatabase.ConnectionString);
runner.MigrateUp(0);
}
public TestDatabase TestDatabase { get; set; }
public override IDbConnection CreateConnection()
{
var connection = new SqlConnection(this.TestDatabase.ConnectionString);
connection.Open();
return connection;
}
public void Dispose()
{
this.TestDatabase.Dispose();
}
}
}
```
Fix unit tests after last set of changes | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestReadModelDatabase.cs">
// Copyright (c) 2015. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Spritely.ReadModel.Sql.Test
{
using System;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using Spritely.Cqrs;
using Spritely.Test.FluentMigratorSqlDatabase;
public class TestReadModelDatabase : ReadModelDatabase<TestReadModelDatabase>, IDisposable
{
public TestReadModelDatabase()
{
this.TestDatabase = new TestDatabase("Create_creates_runner_capable_of_populating_database.mdf");
this.TestDatabase.Create();
this.ConnectionSettings = new DatabaseConnectionSettings();
// Use TestMigration class in this assembly
var runner = FluentMigratorRunnerFactory.Create(Assembly.GetExecutingAssembly(), this.TestDatabase.ConnectionString);
runner.MigrateUp(0);
}
public TestDatabase TestDatabase { get; set; }
public override IDbConnection CreateConnection()
{
var connection = new SqlConnection(this.TestDatabase.ConnectionString);
connection.Open();
return connection;
}
public void Dispose()
{
this.TestDatabase.Dispose();
}
}
}
``` |
e1c48abf-3247-4d95-9415-cb0d2b6e20a9 | {
"language": "C#"
} | ```c#
using EOLib.IO.Map;
namespace EOLib.Domain.Map
{
public class Sign : ISign
{
public string Title { get; private set; }
public string Message { get; private set; }
public Sign(SignMapEntity sign)
{
Title = sign.Title;
Message = sign.Message;
}
}
public interface ISign
{
string Title { get; }
string Message { get; }
}
}
```
Fix rendering of unreadable characters in map signs | ```c#
using EOLib.IO.Map;
using System.Linq;
namespace EOLib.Domain.Map
{
public class Sign : ISign
{
public string Title { get; private set; }
public string Message { get; private set; }
public Sign(SignMapEntity sign)
{
Title = Filter(sign.Title);
Message = Filter(sign.Message);
}
private static string Filter(string input)
{
return new string(input.Where(x => !char.IsControl(x)).ToArray());
}
}
public interface ISign
{
string Title { get; }
string Message { get; }
}
}
``` |
84f31bb1-ff0a-451a-a620-ff166a2df7c5 | {
"language": "C#"
} | ```c#
@{
ViewBag.Title = "Home Page";
ViewBag.ngApp = "MusicStore.Store";
Layout = "/Views/Shared/_Layout.cshtml";
}
@section NavBarItems {
<li app-genre-menu></li>
@*@Html.InlineData("GenreMenuList", "GenresApi")*@
}
<div ng-view></div>
@*@Html.InlineData("MostPopular", "AlbumsApi")*@
@section Scripts {
<script src="~/lib/angular/angular.js"></script>
<script src="~/lig/angular-route/angular-route.js"></script>
@* TODO: This is currently all the compiled TypeScript, non-minified. Need to explore options
for alternate loading schemes, e.g. AMD loader of individual modules, min vs. non-min, etc. *@
<script src="~/js/@(ViewBag.ngApp).js"></script>
}```
Fix typo in MusicStore.Spa page | ```c#
@{
ViewBag.Title = "Home Page";
ViewBag.ngApp = "MusicStore.Store";
Layout = "/Views/Shared/_Layout.cshtml";
}
@section NavBarItems {
<li app-genre-menu></li>
@*@Html.InlineData("GenreMenuList", "GenresApi")*@
}
<div ng-view></div>
@*@Html.InlineData("MostPopular", "AlbumsApi")*@
@section Scripts {
<script src="~/lib/angular/angular.js"></script>
<script src="~/lib/angular-route/angular-route.js"></script>
@* TODO: This is currently all the compiled TypeScript, non-minified. Need to explore options
for alternate loading schemes, e.g. AMD loader of individual modules, min vs. non-min, etc. *@
<script src="~/js/@(ViewBag.ngApp).js"></script>
}``` |
cf602ac1-cf08-4fdb-8886-3e331ff33f98 | {
"language": "C#"
} | ```c#
using System.Linq;
using Should;
namespace Parsley
{
public class GrammarRuleTests : Grammar
{
public void CanDefineMutuallyRecursiveRules()
{
var tokens = new CharLexer().Tokenize("(A)");
var expression = new GrammarRule<string>();
var alpha = new GrammarRule<string>();
var parenthesizedExpresion = new GrammarRule<string>();
expression.Rule = Choice(alpha, parenthesizedExpresion);
alpha.Rule = from a in Token("A") select a.Literal;
parenthesizedExpresion.Rule = Between(Token("("), expression, Token(")"));
expression.Parses(tokens).WithValue("A");
}
public void HasAnOptionallyProvidedName()
{
var unnamed = new GrammarRule<string>();
var named = new GrammarRule<string>("Named");
unnamed.Name.ShouldBeNull();
named.Name.ShouldEqual("Named");
}
public void ProvidesAdviceWhenRuleIsUsedBeforeBeingInitialized()
{
var tokens = new CharLexer().Tokenize("123").ToArray();
var numeric = new GrammarRule<string>();
var alpha = new GrammarRule<string>("Alpha");
numeric.FailsToParse(tokens).WithMessage("(1, 1): An anonymous GrammarRule has not been initialized. Try setting the Rule property.");
alpha.FailsToParse(tokens).WithMessage("(1, 1): GrammarRule 'Alpha' has not been initialized. Try setting the Rule property.");
}
}
}
```
Introduce a bug to prove out CI integration. | ```c#
using System.Linq;
using Should;
namespace Parsley
{
public class GrammarRuleTests : Grammar
{
public void CanDefineMutuallyRecursiveRules()
{
var tokens = new CharLexer().Tokenize("(A)");
var expression = new GrammarRule<string>();
var alpha = new GrammarRule<string>();
var parenthesizedExpresion = new GrammarRule<string>();
expression.Rule = Choice(alpha, parenthesizedExpresion);
alpha.Rule = from a in Token("A") select a.Literal;
parenthesizedExpresion.Rule = Between(Token("("), expression, Token(")"));
expression.Parses(tokens).WithValue("A");
}
public void HasAnOptionallyProvidedName()
{
var unnamed = new GrammarRule<string>();
var named = new GrammarRule<string>("Named<BUG>");
unnamed.Name.ShouldBeNull();
named.Name.ShouldEqual("Named");
}
public void ProvidesAdviceWhenRuleIsUsedBeforeBeingInitialized()
{
var tokens = new CharLexer().Tokenize("123").ToArray();
var numeric = new GrammarRule<string>();
var alpha = new GrammarRule<string>("Alpha");
numeric.FailsToParse(tokens).WithMessage("(1, 1): An anonymous GrammarRule has not been initialized. Try setting the Rule property.");
alpha.FailsToParse(tokens).WithMessage("(1, 1): GrammarRule 'Alpha' has not been initialized. Try setting the Rule property.");
}
}
}
``` |
05673380-4af4-4906-93ce-db69dc296514 | {
"language": "C#"
} | ```c#
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Mvc
{
public class AnyRolesAttribute : ActionFilterAttribute
{
private string[] roles;
public AnyRolesAttribute(string Roles)
{
roles = Roles.Split(',');
for (var i = 0; i < roles.Count(); i++)
roles[i] = roles[i].Trim(' ');
}
public override void OnActionExecuting(ActionExecutingContext context)
{
foreach (var r in roles)
{
if (context.HttpContext.User.IsInRole(r))
base.OnActionExecuting(context);
}
HandleUnauthorizedRequest(context);
}
public virtual void HandleUnauthorizedRequest(ActionExecutingContext context)
{
var prompt = new Prompt
{
Title = "Permission Denied",
StatusCode = 403,
Details = "You must sign in with a higher power account.",
Requires = "Roles",
Hint = roles
};
var services = context.HttpContext.ApplicationServices;
context.Result = new ViewResult
{
StatusCode = prompt.StatusCode,
TempData = new TempDataDictionary(services.GetRequiredService<IHttpContextAccessor>(), services.GetRequiredService<ITempDataProvider>()),
ViewName = "Prompt",
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState) { Model = prompt }
};
}
}
}
```
Fix a bug about any roles attribute | ```c#
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Mvc
{
public class AnyRolesAttribute : ActionFilterAttribute
{
private string[] roles;
public AnyRolesAttribute(string Roles)
{
roles = Roles.Split(',');
for (var i = 0; i < roles.Count(); i++)
roles[i] = roles[i].Trim(' ');
}
public override void OnActionExecuting(ActionExecutingContext context)
{
foreach (var r in roles)
{
if (context.HttpContext.User.IsInRole(r))
{
base.OnActionExecuting(context);
return;
}
}
HandleUnauthorizedRequest(context);
}
public virtual void HandleUnauthorizedRequest(ActionExecutingContext context)
{
var prompt = new Prompt
{
Title = "Permission Denied",
StatusCode = 403,
Details = "You must sign in with a higher power account.",
Requires = "Roles",
Hint = roles
};
var services = context.HttpContext.ApplicationServices;
context.Result = new ViewResult
{
StatusCode = prompt.StatusCode,
TempData = new TempDataDictionary(services.GetRequiredService<IHttpContextAccessor>(), services.GetRequiredService<ITempDataProvider>()),
ViewName = "Prompt",
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState) { Model = prompt }
};
}
}
}
``` |
33c4d3f7-4140-49ac-8b39-f4329d742815 | {
"language": "C#"
} | ```c#
@{
Layout = "_Layout";
ViewData["Title"] = "Guild";
}
<div class="row">
<nav class="col-md-3 col-xl-2">
<ul class="nav">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="GuildList" asp-action="Index">Übersicht</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Guild" asp-controller="Stats" asp-action="Index">Statistiken</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Guild" asp-controller="Mutes" asp-action="Index">Mutes</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Guild" asp-controller="GuildConfig" asp-action="Index">GuildConfig</a>
</li>
</ul>
</nav>
<div class="col-md-9 col-xl-10 py-md-3 pl-md-5">
<div>
<h3>
Server "@ViewBag.Guild.Name" (ID @ViewBag.GuildId)
</h3>
</div>
<div>
@RenderBody()
</div>
</div>
</div>
```
Remove link to guild list from GuildLayout. | ```c#
@{
Layout = "_Layout";
ViewData["Title"] = "Guild";
}
<div class="row">
<nav class="col-md-3 col-xl-2">
<ul class="nav">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Guild" asp-controller="Stats" asp-action="Index">Statistiken</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Guild" asp-controller="Mutes" asp-action="Index">Mutes</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Guild" asp-controller="GuildConfig" asp-action="Index">GuildConfig</a>
</li>
</ul>
</nav>
<div class="col-md-9 col-xl-10 py-md-3 pl-md-5">
<div>
<h3>
Server "@ViewBag.Guild.Name" (ID @ViewBag.GuildId)
</h3>
</div>
<div>
@RenderBody()
</div>
</div>
</div>
``` |
317e0678-1533-449d-a446-74079f644f71 | {
"language": "C#"
} | ```c#
namespace Line.Messaging
{
/// <summary>
/// Rich menu response object.
/// https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object
/// </summary>
public class ResponseRichMenu : RichMenu
{
/// <summary>
/// Rich menu ID
/// </summary>
public string RichMenuId { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="richMenuId">
/// Rich menu ID
/// </param>
/// <param name="source">
/// Rich menu object
/// </param>
public ResponseRichMenu(string richMenuId, RichMenu source)
{
RichMenuId = richMenuId;
Size = source.Size;
Selected = source.Selected;
Name = source.Name;
ChatBarText = source.ChatBarText;
Areas = source.Areas;
}
internal static ResponseRichMenu CreateFrom(dynamic dynamicObject)
{
var menu = new RichMenu()
{
Name = (string)dynamicObject?.name,
Size = new ImagemapSize((int)(dynamicObject?.size?.width ?? 0), (int)(dynamicObject?.size?.height ?? 0)),
Selected = (bool)(dynamicObject?.selected ?? false),
ChatBarText = (string)dynamicObject?.chatBarText
};
return new ResponseRichMenu((string)dynamicObject?.richMenuId, menu);
}
}
}
```
Fix Areas property is not deserialized, In the return value of the GetRichMenuListAsync method. | ```c#
namespace Line.Messaging
{
/// <summary>
/// Rich menu response object.
/// https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object
/// </summary>
public class ResponseRichMenu : RichMenu
{
/// <summary>
/// Rich menu ID
/// </summary>
public string RichMenuId { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="richMenuId">
/// Rich menu ID
/// </param>
/// <param name="source">
/// Rich menu object
/// </param>
public ResponseRichMenu(string richMenuId, RichMenu source)
{
RichMenuId = richMenuId;
Size = source.Size;
Selected = source.Selected;
Name = source.Name;
ChatBarText = source.ChatBarText;
Areas = source.Areas;
}
internal static ResponseRichMenu CreateFrom(dynamic dynamicObject)
{
var menu = new RichMenu()
{
Name = (string)dynamicObject?.name,
Size = new ImagemapSize((int)(dynamicObject?.size?.width ?? 0), (int)(dynamicObject?.size?.height ?? 0)),
Selected = (bool)(dynamicObject?.selected ?? false),
ChatBarText = (string)dynamicObject?.chatBarText,
Areas = ActionArea.CreateFrom(dynamicObject?.areas)
};
return new ResponseRichMenu((string)dynamicObject?.richMenuId, menu);
}
}
}
``` |
cb9ea811-2286-4fde-886b-1e41d3602246 | {
"language": "C#"
} | ```c#
using NQuery.Language.Symbols;
namespace NQuery.Language.VSEditor
{
public sealed class QuickInfoModel
{
private readonly SemanticModel _semanticModel;
private readonly TextSpan _span;
private readonly NQueryGlyph _glyph;
private readonly SymbolMarkup _markup;
public QuickInfoModel(SemanticModel semanticModel, TextSpan span, NQueryGlyph glyph, SymbolMarkup markup)
{
_semanticModel = semanticModel;
_span = span;
_glyph = glyph;
_markup = markup;
}
public static QuickInfoModel ForSymbol(SemanticModel semanticModel, TextSpan span, Symbol symbol)
{
var glyph = symbol.GetGlyph();
var symbolMarkup = SymbolMarkup.ForSymbol(symbol);
return new QuickInfoModel(semanticModel, span, glyph, symbolMarkup);
}
public SemanticModel SemanticModel
{
get { return _semanticModel; }
}
public TextSpan Span
{
get { return _span; }
}
public NQueryGlyph Glyph
{
get { return _glyph; }
}
public SymbolMarkup Markup
{
get { return _markup; }
}
}
}```
Fix quick info to not generate models for invalid symbols | ```c#
using NQuery.Language.Symbols;
namespace NQuery.Language.VSEditor
{
public sealed class QuickInfoModel
{
private readonly SemanticModel _semanticModel;
private readonly TextSpan _span;
private readonly NQueryGlyph _glyph;
private readonly SymbolMarkup _markup;
public QuickInfoModel(SemanticModel semanticModel, TextSpan span, NQueryGlyph glyph, SymbolMarkup markup)
{
_semanticModel = semanticModel;
_span = span;
_glyph = glyph;
_markup = markup;
}
public static QuickInfoModel ForSymbol(SemanticModel semanticModel, TextSpan span, Symbol symbol)
{
if (symbol.Kind == SymbolKind.BadSymbol || symbol.Kind == SymbolKind.BadTable)
return null;
var glyph = symbol.GetGlyph();
var symbolMarkup = SymbolMarkup.ForSymbol(symbol);
return new QuickInfoModel(semanticModel, span, glyph, symbolMarkup);
}
public SemanticModel SemanticModel
{
get { return _semanticModel; }
}
public TextSpan Span
{
get { return _span; }
}
public NQueryGlyph Glyph
{
get { return _glyph; }
}
public SymbolMarkup Markup
{
get { return _markup; }
}
}
}``` |
23adba7d-d632-44d4-8930-c357ad6c0618 | {
"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("SnagitJiraOutputAccessory")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("SnagitJiraOutputAccessory")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0a8197ea-4420-4b56-8734-607694bf6c45")]
// 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")]
```
Update assembly info and start version at 0.1 | ```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("SnagitJiraOutputAccessory")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SnagitJiraOutputAccessory")]
[assembly: AssemblyCopyright("Copyright © Ryan Taylor 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(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0a8197ea-4420-4b56-8734-607694bf6c45")]
// 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.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
``` |
5d849635-65d7-468d-8866-cbb73572f987 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xwt")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Xamarin, Inc (http://www.xamarin.com)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
```
Set a static value so my references quit freaking out. | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xwt")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Xamarin, Inc (http://www.xamarin.com)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
``` |
76649bf5-a032-4ed5-9e51-b7a72d39f8a6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using GitHub.Extensions;
using GitHub.Models;
using GitHub.Services;
using Microsoft.VisualStudio.TeamFoundation.Git.Extensibility;
namespace GitHub.VisualStudio.Base
{
[Export(typeof(IVSGitExt))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class VSGitExt : IVSGitExt
{
IGitExt gitService;
public void Refresh(IServiceProvider serviceProvider)
{
if (gitService != null)
gitService.PropertyChanged -= CheckAndUpdate;
gitService = serviceProvider.GetServiceSafe<IGitExt>();
if (gitService != null)
gitService.PropertyChanged += CheckAndUpdate;
}
void CheckAndUpdate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Guard.ArgumentNotNull(e, nameof(e));
if (e.PropertyName != "ActiveRepositories" || gitService == null)
return;
ActiveRepositoriesChanged?.Invoke();
}
public IEnumerable<ILocalRepositoryModel> ActiveRepositories => gitService?.ActiveRepositories.Select(x => IGitRepositoryInfoExtensions.ToModel(x));
public event Action ActiveRepositoriesChanged;
}
}```
Call extension method as extension method. | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using GitHub.Extensions;
using GitHub.Models;
using GitHub.Services;
using Microsoft.VisualStudio.TeamFoundation.Git.Extensibility;
namespace GitHub.VisualStudio.Base
{
[Export(typeof(IVSGitExt))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class VSGitExt : IVSGitExt
{
IGitExt gitService;
public void Refresh(IServiceProvider serviceProvider)
{
if (gitService != null)
gitService.PropertyChanged -= CheckAndUpdate;
gitService = serviceProvider.GetServiceSafe<IGitExt>();
if (gitService != null)
gitService.PropertyChanged += CheckAndUpdate;
}
void CheckAndUpdate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Guard.ArgumentNotNull(e, nameof(e));
if (e.PropertyName != "ActiveRepositories" || gitService == null)
return;
ActiveRepositoriesChanged?.Invoke();
}
public IEnumerable<ILocalRepositoryModel> ActiveRepositories => gitService?.ActiveRepositories.Select(x => x.ToModel());
public event Action ActiveRepositoriesChanged;
}
}``` |
9a8ff06d-320c-46db-a3ae-df814b9be4b7 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Linq;
using osu.Framework.Input;
using OpenTK.Input;
using osu.Framework.Allocation;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// An overlay container that eagerly holds keyboard focus.
/// </summary>
public abstract class FocusedOverlayContainer : OverlayContainer
{
protected InputManager InputManager;
public override bool RequestingFocus => State == Visibility.Visible;
protected override bool OnFocus(InputState state) => true;
protected override void OnFocusLost(InputState state)
{
if (state.Keyboard.Keys.Contains(Key.Escape))
Hide();
base.OnFocusLost(state);
}
[BackgroundDependencyLoader]
private void load(UserInputManager inputManager)
{
InputManager = inputManager;
}
protected override void PopIn()
{
Schedule(InputManager.TriggerFocusContention);
}
protected override void PopOut()
{
if (HasFocus)
InputManager.ChangeFocus(null);
}
}
}
```
Fix potential nullref due to missing lambda | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Linq;
using osu.Framework.Input;
using OpenTK.Input;
using osu.Framework.Allocation;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// An overlay container that eagerly holds keyboard focus.
/// </summary>
public abstract class FocusedOverlayContainer : OverlayContainer
{
protected InputManager InputManager;
public override bool RequestingFocus => State == Visibility.Visible;
protected override bool OnFocus(InputState state) => true;
protected override void OnFocusLost(InputState state)
{
if (state.Keyboard.Keys.Contains(Key.Escape))
Hide();
base.OnFocusLost(state);
}
[BackgroundDependencyLoader]
private void load(UserInputManager inputManager)
{
InputManager = inputManager;
}
protected override void PopIn()
{
Schedule(() => InputManager.TriggerFocusContention());
}
protected override void PopOut()
{
if (HasFocus)
InputManager.ChangeFocus(null);
}
}
}
``` |
4c2f8a51-a6f7-4d21-b96c-aae072481d46 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.DX11.Internals.Effects.Pins;
using VVVV.PluginInterfaces.V2;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using VVVV.Hosting.Pins;
using VVVV.DX11.Lib.Effects.Pins;
using FeralTic.DX11;
namespace VVVV.DX11.Internals.Effects.Pins
{
public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription>
{
private SamplerState state;
protected override void ProcessAttribute(InputAttribute attr, EffectVariable var)
{
attr.IsSingle = true;
attr.CheckIfChanged = true;
}
protected override bool RecreatePin(EffectVariable var)
{
return false;
}
public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
{
if (this.pin.PluginIO.IsConnected)
{
if (this.pin.IsChanged)
{
if (this.state != null) { this.state.Dispose(); this.state = null; }
}
if (this.state == null || this.state.Disposed)
{
this.state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[0]);
}
shaderinstance.SetByName(this.Name, this.state);
}
else
{
if (this.state != null)
{
this.state.Dispose();
this.state = null;
shaderinstance.SetByName(this.Name, this.state);
}
}
}
}
}```
Fix sampler update when connected | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.DX11.Internals.Effects.Pins;
using VVVV.PluginInterfaces.V2;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using VVVV.Hosting.Pins;
using VVVV.DX11.Lib.Effects.Pins;
using FeralTic.DX11;
namespace VVVV.DX11.Internals.Effects.Pins
{
public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription>
{
private SamplerState state;
protected override void ProcessAttribute(InputAttribute attr, EffectVariable var)
{
attr.IsSingle = true;
attr.CheckIfChanged = true;
}
protected override bool RecreatePin(EffectVariable var)
{
return false;
}
public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
{
if (this.pin.PluginIO.IsConnected)
{
using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice]))
{
shaderinstance.SetByName(this.Name, state);
}
}
else
{
shaderinstance.Effect.GetVariableByName(this.Name).AsConstantBuffer().UndoSetConstantBuffer();
}
}
}
}``` |
7b5f251b-7491-4195-91ce-66b94d9fe02a | {
"language": "C#"
} | ```c#
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PortableWordPressApi;
using PortableWordPressApi.Resources;
namespace ApiConsole
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(AsyncMain());
Console.WriteLine("Press any key to close.");
Console.Read();
}
private static async Task AsyncMain()
{
Console.WriteLine("Enter site URL:");
var url = Console.ReadLine();
Console.WriteLine("Searching for API at {0}", url);
var httpClient = new HttpClient();
var discovery = new WordPressApiDiscovery(new Uri(url, UriKind.Absolute), httpClient);
var api = await discovery.DiscoverApiForSite();
Console.WriteLine("Site's API endpoint: {0}", api.ApiRootUri);
var indexResponse = await httpClient.GetAsync(api.ApiRootUri);
var index = JsonConvert.DeserializeObject<ApiIndex>(await indexResponse.Content.ReadAsStringAsync());
Console.WriteLine("Supported routes: TODO");
}
}
}
```
Print supported routes in console app. | ```c#
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PortableWordPressApi;
using PortableWordPressApi.Resources;
namespace ApiConsole
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(AsyncMain());
Console.WriteLine("Press any key to close.");
Console.Read();
}
private static async Task AsyncMain()
{
Console.WriteLine("Enter site URL:");
var url = Console.ReadLine();
Console.WriteLine("Searching for API at {0}", url);
var httpClient = new HttpClient();
var discovery = new WordPressApiDiscovery(new Uri(url, UriKind.Absolute), httpClient);
var api = await discovery.DiscoverApiForSite();
Console.WriteLine("Site's API endpoint: {0}", api.ApiRootUri);
var indexResponse = await httpClient.GetAsync(api.ApiRootUri);
var index = JsonConvert.DeserializeObject<ApiIndex>(await indexResponse.Content.ReadAsStringAsync());
Console.WriteLine("Supported routes:");
foreach (var route in index.Routes)
{
Console.WriteLine("\t" + route.Key);
}
}
}
}
``` |
57ebf577-f954-4ad5-b64a-2d6e5c6342a5 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Allocation
{
/// <summary>
/// Denotes a component which performs long-running tasks in its <see cref="BackgroundDependencyLoaderAttribute"/> method that are not CPU intensive.
/// This will force a consumer to use <see cref="CompositeDrawable.LoadComponentAsync{TLoadable}"/> when loading the components, and also schedule them in a lower priority pool.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class LongRunningLoadAttribute : Attribute
{
}
}
```
Adjust xmldoc to mention "immediate" consumer | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Allocation
{
/// <summary>
/// Denotes a component which performs long-running tasks in its <see cref="BackgroundDependencyLoaderAttribute"/> method that are not CPU intensive.
/// Long-running tasks are scheduled into a lower priority thread pool.
/// </summary>
/// <remarks>
/// This forces immediate consumers to use <see cref="CompositeDrawable.LoadComponentAsync{TLoadable}"/> when loading the component.
/// </remarks>
[AttributeUsage(AttributeTargets.Class)]
public class LongRunningLoadAttribute : Attribute
{
}
}
``` |
6c2f5142-5d8b-4d97-8ac2-a8a9ed3d81f0 | {
"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.Configuration;
using osu.Framework.Platform;
namespace osu.Game.Tournament.Configuration
{
public class TournamentStorageManager : IniConfigManager<StorageConfig>
{
protected override string Filename => "tournament.ini";
public TournamentStorageManager(Storage storage)
: base(storage)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(StorageConfig.CurrentTournament, string.Empty);
}
}
public enum StorageConfig
{
CurrentTournament,
}
}
```
Remove default value in Storagemgr | ```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.Configuration;
using osu.Framework.Platform;
namespace osu.Game.Tournament.Configuration
{
public class TournamentStorageManager : IniConfigManager<StorageConfig>
{
protected override string Filename => "tournament.ini";
public TournamentStorageManager(Storage storage)
: base(storage)
{
}
}
public enum StorageConfig
{
CurrentTournament,
}
}
``` |
a12aac08-5bf9-48de-b0ea-85b35b99c853 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Internal.TypeSystem
{
// Implements canonicalization for arrays
partial class ArrayType
{
protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind)
{
TypeDesc paramTypeConverted = CanonUtilites.ConvertToCanon(ParameterType, kind);
if (paramTypeConverted != ParameterType)
{
// Note: don't use the Rank property here, as that hides the difference
// between a single dimensional MD array and an SZArray.
return Context.GetArrayType(paramTypeConverted, _rank);
}
return this;
}
}
}```
Add canonicalization support for array methods | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Internal.TypeSystem
{
// Implements canonicalization for arrays
partial class ArrayType
{
protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind)
{
TypeDesc paramTypeConverted = CanonUtilites.ConvertToCanon(ParameterType, kind);
if (paramTypeConverted != ParameterType)
{
// Note: don't use the Rank property here, as that hides the difference
// between a single dimensional MD array and an SZArray.
return Context.GetArrayType(paramTypeConverted, _rank);
}
return this;
}
}
// Implements canonicalization for array methods
partial class ArrayMethod
{
public override bool IsCanonicalMethod(CanonicalFormKind policy)
{
return _owningType.IsCanonicalSubtype(policy);
}
public override MethodDesc GetCanonMethodTarget(CanonicalFormKind kind)
{
TypeDesc canonicalizedTypeOfTargetMethod = _owningType.ConvertToCanonForm(kind);
if (canonicalizedTypeOfTargetMethod == _owningType)
return this;
return ((ArrayType)canonicalizedTypeOfTargetMethod).GetArrayMethod(_kind);
}
}
}``` |
41a2c7f8-2d8c-4b54-a4b6-85cef08691fc | {
"language": "C#"
} | ```c#
using System.Configuration;
namespace NStatsD
{
public class StatsDConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("enabled", DefaultValue = "true", IsRequired = false)]
public bool Enabled
{
get { return (bool) this["enabled"]; }
set { this["enabled"] = value; }
}
[ConfigurationProperty("server")]
public ServerElement Server
{
get { return (ServerElement) this["server"]; }
set { this["server"] = value; }
}
[ConfigurationProperty("prefix", DefaultValue = "", IsRequired = false)]
public string Prefix
{
get { return (string)this["prefix"]; }
set { this["prefix"] = value; }
}
}
public class ServerElement : ConfigurationElement
{
[ConfigurationProperty("host", DefaultValue = "localhost", IsRequired = true)]
public string Host
{
get { return (string) this["host"]; }
set { this["host"] = value; }
}
[ConfigurationProperty("port", DefaultValue = "8125", IsRequired = false)]
public int Port
{
get { return (int) this["port"]; }
set { this["port"] = value; }
}
}
}
```
Fix exception when configuration is read | ```c#
using System.Configuration;
namespace NStatsD
{
public class StatsDConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("enabled", DefaultValue = "true", IsRequired = false)]
public bool Enabled
{
get { return (bool) this["enabled"]; }
set { this["enabled"] = value; }
}
[ConfigurationProperty("server")]
public ServerElement Server
{
get { return (ServerElement) this["server"]; }
set { this["server"] = value; }
}
[ConfigurationProperty("prefix", DefaultValue = "", IsRequired = false)]
public string Prefix
{
get { return (string)this["prefix"]; }
set { this["prefix"] = value; }
}
public override bool IsReadOnly()
{
return false;
}
}
public class ServerElement : ConfigurationElement
{
[ConfigurationProperty("host", DefaultValue = "localhost", IsRequired = true)]
public string Host
{
get { return (string) this["host"]; }
set { this["host"] = value; }
}
[ConfigurationProperty("port", DefaultValue = "8125", IsRequired = false)]
public int Port
{
get { return (int) this["port"]; }
set { this["port"] = value; }
}
}
}
``` |
3f760c21-9a6b-4e95-9c7f-c1a978d2ea5c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Magecrawl.GameEngine.Actors;
using Magecrawl.Utilities;
namespace Magecrawl.GameEngine.Affects
{
internal class Haste : AffectBase
{
private double m_modifier;
public Haste() : base(0)
{
}
public Haste(int strength)
: base(new DiceRoll(1, 4, strength).Roll() * CoreTimingEngine.CTNeededForNewTurn)
{
m_modifier = 1 + (.2 * strength);
}
public override void Apply(Character appliedTo)
{
appliedTo.CTIncreaseModifier *= m_modifier;
}
public override void Remove(Character removedFrom)
{
removedFrom.CTIncreaseModifier /= m_modifier;
}
public override string Name
{
get
{
return "Haste";
}
}
#region SaveLoad
public override void ReadXml(System.Xml.XmlReader reader)
{
base.ReadXml(reader);
m_modifier = reader.ReadContentAsDouble();
}
public override void WriteXml(System.Xml.XmlWriter writer)
{
base.WriteXml(writer);
writer.WriteElementString("Modifier", m_modifier.ToString());
}
#endregion
}
}
```
Fix crash on loading hasted player. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Magecrawl.GameEngine.Actors;
using Magecrawl.Utilities;
namespace Magecrawl.GameEngine.Affects
{
internal class Haste : AffectBase
{
private double m_modifier;
public Haste() : base(0)
{
}
public Haste(int strength)
: base(new DiceRoll(1, 4, strength).Roll() * CoreTimingEngine.CTNeededForNewTurn)
{
m_modifier = 1 + (.2 * strength);
}
public override void Apply(Character appliedTo)
{
appliedTo.CTIncreaseModifier *= m_modifier;
}
public override void Remove(Character removedFrom)
{
removedFrom.CTIncreaseModifier /= m_modifier;
}
public override string Name
{
get
{
return "Haste";
}
}
#region SaveLoad
public override void ReadXml(System.Xml.XmlReader reader)
{
base.ReadXml(reader);
m_modifier = reader.ReadElementContentAsDouble();
}
public override void WriteXml(System.Xml.XmlWriter writer)
{
base.WriteXml(writer);
writer.WriteElementString("Modifier", m_modifier.ToString());
}
#endregion
}
}
``` |
75f7b192-972d-435c-9d35-9db98ba67631 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Sage.Platform;
using Sage.Platform.Orm.Attributes;
using Sage.Platform.Orm.Interfaces;
namespace OpenSlx.Lib.Utility
{
/// <summary>
/// Miscellaneous utilities dealing with SLX entities.
/// </summary>
public static class SlxEntityUtility
{
public static T CloneEntity<T>(T source)
where T : IDynamicEntity
{
T target = EntityFactory.Create<T>();
foreach (PropertyInfo prop in source.GetType().GetProperties())
{
if (Attribute.GetCustomAttribute(prop, typeof(FieldAttribute)) != null)
{
target[prop.Name] = source[prop.Name];
}
}
return target;
}
}
}
```
Add check for Standard Id in CloneEntity, and add a CopyEntityProperties method to allow calling it separately | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Sage.Platform;
using Sage.Platform.Orm.Attributes;
using Sage.Platform.Orm.Interfaces;
using Sage.Platform.Orm.Services;
namespace OpenSlx.Lib.Utility
{
/// <summary>
/// Miscellaneous utilities dealing with SLX entities.
/// </summary>
public static class SlxEntityUtility
{
/// <summary>
/// Create a copy of an existing entity
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T CloneEntity<T>(T source)
where T : IDynamicEntity
{
T target = EntityFactory.Create<T>();
CopyEntityProperties(target, source);
return target;
}
public static void CopyEntityProperties<T>(T target, T source)
where T : IDynamicEntity
{
foreach (PropertyInfo prop in source.GetType().GetProperties())
{
// only copy the ones associated with DB fields
// (note that this includes M-1 relationships)
if (Attribute.GetCustomAttribute(prop, typeof(FieldAttribute)) != null)
{
var extendedType =
(DynamicEntityDescriptorConfigurationService.ExtendedTypeInformationAttribute)
prop.GetCustomAttributes(
typeof(DynamicEntityDescriptorConfigurationService.ExtendedTypeInformationAttribute),
false).FirstOrDefault();
// don't copy ID fields - we'll pick up the reference properties instead
if (extendedType != null && extendedType.ExtendedTypeName ==
"Sage.Platform.Orm.DataTypes.StandardIdDataType, Sage.Platform")
{
continue;
}
target[prop.Name] = source[prop.Name];
}
}
}
}
}
``` |
331377ec-ef93-4368-9e4d-2298c997c2b7 | {
"language": "C#"
} | ```c#
using System;
using System.Net;
using System.Text;
using System.Threading;
using xServer.Settings;
namespace xServer.Core.Misc
{
public static class NoIpUpdater
{
private static bool _running;
public static void Start()
{
if (_running) return;
Thread updateThread = new Thread(BackgroundUpdater) {IsBackground = true};
updateThread.Start();
}
private static void BackgroundUpdater()
{
_running = true;
while (XMLSettings.IntegrateNoIP)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://dynupdate.no-ip.com/nic/update?hostname={0}", XMLSettings.NoIPHost));
request.UserAgent = string.Format("xRAT No-Ip Updater/2.0 {0}", XMLSettings.NoIPUsername);
request.Timeout = 10000;
request.Headers.Add(HttpRequestHeader.Authorization, string.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", XMLSettings.NoIPUsername, XMLSettings.NoIPPassword)))));
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
}
}
catch
{
}
Thread.Sleep(TimeSpan.FromMinutes(10));
}
_running = false;
}
}
}
```
Set Proxy to null when sending the No-Ip DNS Update request | ```c#
using System;
using System.Net;
using System.Text;
using System.Threading;
using xServer.Settings;
namespace xServer.Core.Misc
{
public static class NoIpUpdater
{
private static bool _running;
public static void Start()
{
if (_running) return;
Thread updateThread = new Thread(BackgroundUpdater) {IsBackground = true};
updateThread.Start();
}
private static void BackgroundUpdater()
{
_running = true;
while (XMLSettings.IntegrateNoIP)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://dynupdate.no-ip.com/nic/update?hostname={0}", XMLSettings.NoIPHost));
request.Proxy = null;
request.UserAgent = string.Format("xRAT No-Ip Updater/2.0 {0}", XMLSettings.NoIPUsername);
request.Timeout = 10000;
request.Headers.Add(HttpRequestHeader.Authorization, string.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", XMLSettings.NoIPUsername, XMLSettings.NoIPPassword)))));
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
}
}
catch
{
}
Thread.Sleep(TimeSpan.FromMinutes(10));
}
_running = false;
}
}
}
``` |
6c3f9f38-050f-483f-975b-47a2e23ce2a7 | {
"language": "C#"
} | ```c#
using revashare_svc_webapi.Logic;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace revashare_svc_webapi.Tests
{
public class FlagTests
{
[Fact]
public void test_GetFlags()
{
RevaShareDataServiceClient dataClient = new RevaShareDataServiceClient();
List<FlagDAO> getflags = dataClient.GetAllFlags().ToList();
Assert.NotNull(getflags);
}
[Fact]
public void test_GetFlags_AdminLogic()
{
AdminLogic admLogic = new AdminLogic();
var a = admLogic.GetUserReports();
Assert.NotEmpty(a);
}
[Fact]
public void test_RemoveReport_AdminLogic()
{
AdminLogic admLogic = new AdminLogic();
}
}
}
```
Check to see if merge worked | ```c#
using revashare_svc_webapi.Logic;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace revashare_svc_webapi.Tests
{
public class FlagTests
{
[Fact]
public void test_GetFlags()
{
RevaShareDataServiceClient dataClient = new RevaShareDataServiceClient();
List<FlagDAO> getflags = dataClient.GetAllFlags().ToList();
Assert.NotNull(getflags);
}
[Fact]
public void test_GetFlags_AdminLogic()
{
AdminLogic admLogic = new AdminLogic();
var a = admLogic.GetUserReports();
Assert.NotEmpty(a);
}
//[Fact]
//public void test_RemoveReport_AdminLogic()
//{
// AdminLogic admLogic = new AdminLogic();
//}
}
}
``` |
6ac663f0-a2b8-4d6c-9a47-7c3ebae347b9 | {
"language": "C#"
} | ```c#
using AspNetCore.Security.CAS;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CookieSample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Setup based on https://github.com/aspnet/Security/tree/rel/2.0.0/samples/SocialSample
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.LoginPath = new PathString("/login");
o.Cookie = new CookieBuilder
{
Name = ".AspNet.CasSample"
};
})
.AddCAS(o =>
{
o.CasServerUrlBase = Configuration["CasBaseUrl"];
o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
}
}
```
Add comment to help find CAS url setting | ```c#
using AspNetCore.Security.CAS;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CookieSample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Setup based on https://github.com/aspnet/Security/tree/rel/2.0.0/samples/SocialSample
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.LoginPath = new PathString("/login");
o.Cookie = new CookieBuilder
{
Name = ".AspNet.CasSample"
};
})
.AddCAS(o =>
{
o.CasServerUrlBase = Configuration["CasBaseUrl"]; // Set in `appsettings.json` file.
o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
}
}
``` |
b105ac21-2331-464c-b5d7-be6ddd72789c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using RedditSharp.Things;
namespace RedditSharp.PowerShell.Cmdlets.Posts
{
/// <summary>
/// <para type="description">Edit the text of a self post. Will not work on link posts.</para>
/// </summary>
[Cmdlet(VerbsData.Edit,"Post")]
[OutputType(typeof(Post))]
public class EditPost : Cmdlet
{
[Parameter(Mandatory=true,Position = 0,HelpMessage = "Self post to edit")]
public Post Target { get; set; }
[Parameter(Mandatory = true,Position = 1,HelpMessage = "New body text/markdown.")]
public string Body { get; set; }
protected override void BeginProcessing()
{
if (Session.Reddit == null)
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(), "NoRedditSession",
ErrorCategory.InvalidOperation, Session.Reddit));
}
protected override void ProcessRecord()
{
try
{
Target.EditText(Body);
Target.SelfText = Body;
WriteObject(Target);
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "CantUpdateSelfText", ErrorCategory.InvalidOperation, Target));
}
}
}
}
```
Change to InputObject naming convention | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using RedditSharp.Things;
namespace RedditSharp.PowerShell.Cmdlets.Posts
{
/// <summary>
/// <para type="description">Edit the text of a self post. Will not work on link posts.</para>
/// </summary>
[Cmdlet(VerbsData.Edit,"Post")]
[OutputType(typeof(Post))]
public class EditPost : Cmdlet
{
[Parameter(Mandatory=true,Position = 0,HelpMessage = "Self post to edit")]
public Post InputObject { get; set; }
[Parameter(Mandatory = true,Position = 1,HelpMessage = "New body text/markdown.")]
public string Body { get; set; }
protected override void BeginProcessing()
{
if (Session.Reddit == null)
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(), "NoRedditSession",
ErrorCategory.InvalidOperation, Session.Reddit));
}
protected override void ProcessRecord()
{
try
{
InputObject.EditText(Body);
InputObject.SelfText = Body;
WriteObject(InputObject);
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "CantUpdateSelfText", ErrorCategory.InvalidOperation, InputObject));
}
}
}
}
``` |
58cb188a-2ed7-4c2f-8eba-603a9b16423c | {
"language": "C#"
} | ```c#
using Bam.Core;
namespace boost
{
abstract class GenericBoostModule :
C.StaticLibrary
{
protected GenericBoostModule(
string name)
{
this.Name = name;
}
private string Name
{
get;
set;
}
protected C.Cxx.ObjectFileCollection BoostSource
{
get;
private set;
}
protected override void
Init(
Bam.Core.Module parent)
{
base.Init(parent);
this.Macros["OutputName"] = TokenizedString.CreateVerbatim(string.Format("boost_{0}-vc120-mt-1_60", this.Name));
this.Macros["libprefix"] = TokenizedString.CreateVerbatim("lib");
this.BoostSource = this.CreateCxxSourceContainer();
this.CompileAgainstPublicly<BoostHeaders>(this.BoostSource);
if (this.BuildEnvironment.Platform.Includes(EPlatform.Windows))
{
this.BoostSource.PrivatePatch(settings =>
{
var cxxCompiler = settings as C.ICxxOnlyCompilerSettings;
cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Asynchronous;
});
if (this.Librarian is VisualCCommon.Librarian)
{
this.CompileAgainst<WindowsSDK.WindowsSDK>(this.BoostSource);
}
}
}
}
}
```
Set VisualC warning level that a warning free compile occurs | ```c#
using Bam.Core;
namespace boost
{
abstract class GenericBoostModule :
C.StaticLibrary
{
protected GenericBoostModule(
string name)
{
this.Name = name;
}
private string Name
{
get;
set;
}
protected C.Cxx.ObjectFileCollection BoostSource
{
get;
private set;
}
protected override void
Init(
Bam.Core.Module parent)
{
base.Init(parent);
this.Macros["OutputName"] = TokenizedString.CreateVerbatim(string.Format("boost_{0}-vc120-mt-1_60", this.Name));
this.Macros["libprefix"] = TokenizedString.CreateVerbatim("lib");
this.BoostSource = this.CreateCxxSourceContainer();
this.CompileAgainstPublicly<BoostHeaders>(this.BoostSource);
if (this.BuildEnvironment.Platform.Includes(EPlatform.Windows))
{
this.BoostSource.PrivatePatch(settings =>
{
var cxxCompiler = settings as C.ICxxOnlyCompilerSettings;
cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Asynchronous;
var vcCompiler = settings as VisualCCommon.ICommonCompilerSettings;
if (null != vcCompiler)
{
vcCompiler.WarningLevel = VisualCCommon.EWarningLevel.Level2; // does not compile warning-free above this level
}
});
if (this.Librarian is VisualCCommon.Librarian)
{
this.CompileAgainst<WindowsSDK.WindowsSDK>(this.BoostSource);
}
}
}
}
}
``` |
76df8805-6dac-4201-8e8c-a5eb3a69643d | {
"language": "C#"
} | ```c#
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// 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("4.1.2.0")]
[assembly: AssemblyFileVersion("4.1.2.0")]
```
Bump the version to v4.1.3 | ```c#
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// 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("4.1.3.0")]
[assembly: AssemblyFileVersion("4.1.3.0")]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.