doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
2be2cb01-646f-4d0d-8d7c-313b0ec343f6 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Configuration;
using osu.Framework.Platform;
namespace osu.Framework.Testing
{
internal class TestBrowserConfig : IniConfigManager<TestBrowserSetting>
{
protected override string Filename => @"visualtests.cfg";
public TestBrowserConfig(Storage storage) : base(storage)
{
}
}
internal enum TestBrowserSetting
{
LastTest,
}
}
```
Fix VisualTests crashing on first startup due to incorrect configuration | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Configuration;
using osu.Framework.Platform;
namespace osu.Framework.Testing
{
internal class TestBrowserConfig : IniConfigManager<TestBrowserSetting>
{
protected override string Filename => @"visualtests.cfg";
public TestBrowserConfig(Storage storage) : base(storage)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(TestBrowserSetting.LastTest, string.Empty);
}
}
internal enum TestBrowserSetting
{
LastTest,
}
}
``` |
689ddb3e-da05-4f21-afca-fc9e00651055 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using NUnit.Framework;
namespace Mango.Server.Tests
{
[TestFixture()]
public class HttpHeadersTest
{
[Test()]
public void TestMultilineParse ()
{
//
// multiline values are acceptable if the next
// line starts with spaces
//
string header = @"HeaderName: Some multiline
value";
HttpHeaders headers = new HttpHeaders ();
headers.Parse (new StringReader (header));
Assert.AreEqual ("some multiline value", headers ["HeaderName"], "a1");
}
}
}
```
Make sure we test across more than two lines. | ```c#
using System;
using System.IO;
using NUnit.Framework;
namespace Mango.Server.Tests
{
[TestFixture()]
public class HttpHeadersTest
{
[Test()]
public void TestMultilineParse ()
{
//
// multiline values are acceptable if the next
// line starts with spaces
//
string header = @"HeaderName: Some multiline
value";
HttpHeaders headers = new HttpHeaders ();
headers.Parse (new StringReader (header));
Assert.AreEqual ("some multiline value", headers ["HeaderName"], "a1");
header = @"HeaderName: Some multiline
value
that spans
a bunch of lines";
headers = new HttpHeaders ();
headers.Parse (new StringReader (header));
Assert.AreEqual ("Some multiline value that spans a bunch of lines", headers ["HeaderName"], "a2");
}
}
}
``` |
4b146931-6a5a-40bb-a8f2-482137b1d4f8 | {
"language": "C#"
} | ```c#
namespace CypherTwo.Tests
{
using System;
using System.Net.Http;
using CypherTwo.Core;
using NUnit.Framework;
[TestFixture]
public class IntegrationTests
{
private INeoClient neoClient;
private ISendRestCommandsToNeo neoApi;
private IJsonHttpClientWrapper httpClientWrapper;
[SetUp]
public void SetupBeforeEachTest()
{
this.httpClientWrapper = new JsonHttpClientWrapper(new HttpClient());
this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:7474/");
this.neoClient = new NeoClient(this.neoApi);
this.neoClient.Initialise();
}
[Test]
public void InitialiseThrowsExecptionWithInvalidUrl()
{
this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:1111/");
this.neoClient = new NeoClient(this.neoApi);
Assert.Throws<InvalidOperationException>(() => this.neoClient.Initialise());
}
[Test]
public async void CreateAndSelectNode()
{
var reader = await this.neoClient.QueryAsync("CREATE (n:Person { name : 'Andres', title : 'Developer' }) RETURN Id(n)");
Assert.That(reader.Read(), Is.EqualTo(true));
Assert.That(reader.Get<int>(0), Is.EqualTo(1));
}
}
}```
Change URL of initialization in integration tests | ```c#
namespace CypherTwo.Tests
{
using System;
using System.Net.Http;
using CypherTwo.Core;
using NUnit.Framework;
[TestFixture]
public class IntegrationTests
{
private INeoClient neoClient;
private ISendRestCommandsToNeo neoApi;
private IJsonHttpClientWrapper httpClientWrapper;
[SetUp]
public void SetupBeforeEachTest()
{
this.httpClientWrapper = new JsonHttpClientWrapper(new HttpClient());
this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:7474/db/data");
this.neoClient = new NeoClient(this.neoApi);
this.neoClient.Initialise();
}
[Test]
public void InitialiseThrowsExecptionWithInvalidUrl()
{
this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:1111/");
this.neoClient = new NeoClient(this.neoApi);
Assert.Throws<InvalidOperationException>(() => this.neoClient.Initialise());
}
[Test]
public async void CreateAndSelectNode()
{
var reader = await this.neoClient.QueryAsync("CREATE (n:Person { name : 'Andres', title : 'Developer' }) RETURN Id(n)");
Assert.That(reader.Read(), Is.EqualTo(true));
Assert.That(reader.Get<int>(0), Is.EqualTo(1));
}
}
}``` |
36678ce3-61cc-4222-8db0-b17dff3b0a5e | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
namespace Template10.Samples.SearchSample
{
sealed partial class App : Template10.Common.BootStrapper
{
public App()
{
InitializeComponent();
}
public override Task OnInitializeAsync(IActivatedEventArgs args)
{
var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include, null);
Window.Current.Content = new Views.Shell(nav);
return Task.CompletedTask;
}
public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
NavigationService.Navigate(typeof(Views.MainPage));
return Task.CompletedTask;
}
}
}
```
Fix Object reference not set to an instance of an object. | ```c#
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
namespace Template10.Samples.SearchSample
{
sealed partial class App : Template10.Common.BootStrapper
{
public App()
{
InitializeComponent();
}
public override Task OnInitializeAsync(IActivatedEventArgs args)
{
var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
Window.Current.Content = new Views.Shell(nav);
return Task.CompletedTask;
}
public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
NavigationService.Navigate(typeof(Views.MainPage));
return Task.CompletedTask;
}
}
}
``` |
585f38a1-5c6a-484e-b4e2-c88b30401565 | {
"language": "C#"
} | ```c#
using Glimpse.Web;
using System;
namespace Glimpse.Agent.Web
{
public class AgentRuntime : IRequestRuntime
{
private readonly IMessagePublisher _messagePublisher;
public AgentRuntime(IMessagePublisher messagePublisher)
{
_messagePublisher = messagePublisher;
}
public void Begin(IContext newContext)
{
var message = new BeginRequestMessage();
// TODO: Full out message more
_messagePublisher.PublishMessage(message);
}
public void End(IContext newContext)
{
var message = new EndRequestMessage();
// TODO: Full out message more
_messagePublisher.PublishMessage(message);
}
}
}```
Switch over agent to using Agent bus | ```c#
using Glimpse.Web;
using System;
namespace Glimpse.Agent.Web
{
public class AgentRuntime : IRequestRuntime
{
private readonly IMessageAgentBus _messageBus;
public AgentRuntime(IMessageAgentBus messageBus)
{
_messageBus = messageBus;
}
public void Begin(IContext newContext)
{
var message = new BeginRequestMessage();
// TODO: Full out message more
_messageBus.SendMessage(message);
}
public void End(IContext newContext)
{
var message = new EndRequestMessage();
// TODO: Full out message more
_messageBus.SendMessage(message);
}
}
}``` |
b6ac9eb2-ffeb-4f8e-a54d-5957cb31a725 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Wangkanai.Detection.Models;
using Wangkanai.Detection.Services;
namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
[HtmlTargetElement(ElementName, Attributes = OnlyAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)]
public class PreferenceTagHelper : TagHelper
{
private const string ElementName = "preference";
private const string OnlyAttributeName = "only";
protected IHtmlGenerator Generator { get; }
private readonly IResponsiveService _responsive;
private readonly IDeviceService _device;
[HtmlAttributeName(OnlyAttributeName)] public string? Only { get; set; }
public PreferenceTagHelper(IHtmlGenerator generator, IResponsiveService responsive, IDeviceService device)
{
Generator = generator ?? throw new ArgumentNullException(nameof(generator));
_responsive = responsive ?? throw new ArgumentNullException(nameof(responsive));
_device = device ?? throw new ArgumentNullException(nameof(device));
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (output == null)
throw new ArgumentNullException(nameof(output));
output.TagName = null;
if (string.IsNullOrWhiteSpace(Only))
return;
if (!_responsive.HasPreferred() && !DisplayOnlyDevice)
output.SuppressOutput();
}
private bool DisplayOnlyDevice => _device.Type == OnlyDevice;
private Device OnlyDevice => Enum.Parse<Device>(Only, true);
}
}```
Use positive statement and let it return as soon as possible | ```c#
using System;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Wangkanai.Detection.Models;
using Wangkanai.Detection.Services;
namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
[HtmlTargetElement(ElementName, Attributes = OnlyAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)]
public class PreferenceTagHelper : TagHelper
{
private const string ElementName = "preference";
private const string OnlyAttributeName = "only";
protected IHtmlGenerator Generator { get; }
private readonly IResponsiveService _responsive;
private readonly IDeviceService _device;
[HtmlAttributeName(OnlyAttributeName)] public string? Only { get; set; }
public PreferenceTagHelper(IHtmlGenerator generator, IResponsiveService responsive, IDeviceService device)
{
Generator = generator ?? throw new ArgumentNullException(nameof(generator));
_responsive = responsive ?? throw new ArgumentNullException(nameof(responsive));
_device = device ?? throw new ArgumentNullException(nameof(device));
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (output == null)
throw new ArgumentNullException(nameof(output));
output.TagName = null;
if (string.IsNullOrWhiteSpace(Only))
return;
if (_responsive.HasPreferred())
return;
if (DisplayOnlyDevice)
return;
output.SuppressOutput();
}
private bool DisplayOnlyDevice => _device.Type == OnlyDevice;
private Device OnlyDevice => Enum.Parse<Device>(Only, true);
}
}``` |
6be83480-7598-4764-b1f8-95c81c3a23ec | {
"language": "C#"
} | ```c#
@{
ViewBag.Title = "Search";
}
<div class="col">
<form asp-controller="Lab" asp-action="Search">
<div>
<div class="form-group">
<label class="control-label">Search By Id, Request Num, or Share Identifier</label>
<div>
<input id="term" class="form-control" name="term" />
</div>
</div>
<button type="submit" class="btn btn-danger"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
</div>
</form>
</div>
```
Put auto focus on search too | ```c#
@{
ViewBag.Title = "Search";
}
<div class="col">
<form asp-controller="Lab" asp-action="Search">
<div>
<div class="form-group">
<label class="control-label">Search By Id, Request Num, or Share Identifier</label>
<div>
<input id="term" class="form-control" name="term" autofocus />
</div>
</div>
<button type="submit" class="btn btn-danger"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
</div>
</form>
</div>
``` |
4f2deef6-c178-4bd4-93b0-125cb5c21eed | {
"language": "C#"
} | ```c#
using System;
using Xunit;
using SolutionEdit;
namespace SolutionParserTest
{
public class ProjectTest
{
[Fact]
public void CreateNewDirectoryProject()
{
// Arrange.
var directoryName = "Test";
// Act.
var directoryProject = Project.NewDirectoryProject(directoryName);
// Assert.
Assert.Equal(directoryName, directoryProject.Name);
Assert.Equal(directoryName, directoryProject.Location);
Assert.Equal(ProjectType.Directory, directoryProject.Type);
}
}
}
```
Add unit test for reading a project definition. | ```c#
using System;
using Xunit;
using SolutionEdit;
using System.IO;
namespace SolutionParserTest
{
public class ProjectTest
{
[Fact]
public void CreateNewDirectoryProject()
{
// Arrange.
var directoryName = "Test";
// Act.
var directoryProject = Project.NewDirectoryProject(directoryName);
// Assert.
Assert.Equal(directoryName, directoryProject.Name);
Assert.Equal(directoryName, directoryProject.Location);
Assert.Equal(ProjectType.Directory, directoryProject.Type);
}
[Fact]
public void ReadProjectFromStream()
{
// Project is of the form:
//Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SolutionParser", "SolutionParser\SolutionParser.csproj", "{AE17D442-B29B-4F55-9801-7151BCD0D9CA}"
//EndProject
// Arrange.
var guid = new Guid("1DC4FA2D-16D1-459D-9C35-D49208F753C5");
var projectName = "TestProject";
var projectLocation = @"This\is\a\test\TestProject.csproj";
var projectDefinition = $"Project(\"{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}\") = \"{projectName}\", \"{projectLocation}\", \"{guid.ToString("B").ToUpper()}\"\nEndProject";
using (TextReader inStream = new StringReader(projectDefinition))
{
// Act.
var project = new Project(inStream);
// Assert.
Assert.Equal(projectName, project.Name);
Assert.Equal(projectLocation, project.Location);
Assert.Equal(ProjectType.Project, project.Type);
}
}
}
}
``` |
62518cd4-4527-4bf4-b50b-937e118fbc7d | {
"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("TinCan")]
[assembly: AssemblyDescription("Library for implementing Tin Can API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rustici Software")]
[assembly: AssemblyProduct("TinCan")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6b7c12d3-32ea-4cb2-9399-3004963d2340")]
// 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.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
```
Update product name in 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("TinCan")]
[assembly: AssemblyDescription("Library for implementing Tin Can API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rustici Software")]
[assembly: AssemblyProduct("TinCan.NET")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6b7c12d3-32ea-4cb2-9399-3004963d2340")]
// 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.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
``` |
cc555570-17bc-42e5-9da3-5bd1f3da0dfb | {
"language": "C#"
} | ```c#
using Flood.RPC.Server;
using Flood.RPC.Transport;
namespace Flood.Server
{
public abstract class Server
{
public IDatabaseManager Database { get; set; }
public TSimpleServer RPCServer { get; set; }
public TServerSocket Socket { get; set; }
protected Server()
{
#if RAVENDBSET
Database = new RavenDatabaseManager();
#else
Database = new NullDatabaseManager();
#endif
}
public void Shutdown()
{
}
public void Update()
{
}
}
}```
Change the feature define to be more uniform. | ```c#
using Flood.RPC.Server;
using Flood.RPC.Transport;
namespace Flood.Server
{
public abstract class Server
{
public IDatabaseManager Database { get; set; }
public TSimpleServer RPCServer { get; set; }
public TServerSocket Socket { get; set; }
protected Server()
{
#if USE_RAVENDB
Database = new RavenDatabaseManager();
#else
Database = new NullDatabaseManager();
#endif
}
public void Shutdown()
{
}
public void Update()
{
}
}
}``` |
5d876af1-7d63-45c8-8d03-ec7e7f720a0a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YoutubeExtractor;
namespace VideoLibrary.Debug
{
class Program
{
static void Main(string[] args)
{
string[] queries =
{
// test queries, borrowed from
// github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/youtube.py
// "http://www.youtube.com/watch?v=6kLq3WMV1nU",
// "http://www.youtube.com/watch?v=6kLq3WMV1nU",
"https://www.youtube.com/watch?v=IB3lcPjvWLA",
"https://www.youtube.com/watch?v=BgpXMA_M98o"
};
using (var cli = Client.For(YouTube.Default))
{
for (int i = 0; i < queries.Length; i++)
{
string query = queries[i];
var video = cli.GetVideo(query);
string uri = video.Uri;
string otherUri = DownloadUrlResolver
.GetDownloadUrls(query).First()
.DownloadUrl;
}
}
}
}
}
```
Add test URL to libvideo.debug | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YoutubeExtractor;
namespace VideoLibrary.Debug
{
class Program
{
static void Main(string[] args)
{
string[] queries =
{
// test queries, borrowed from
// github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/youtube.py
// "http://www.youtube.com/watch?v=6kLq3WMV1nU",
// "http://www.youtube.com/watch?v=6kLq3WMV1nU",
"https://www.youtube.com/watch?v=IB3lcPjvWLA",
"https://www.youtube.com/watch?v=BgpXMA_M98o",
"https://www.youtube.com/watch?v=nfWlot6h_JM"
};
using (var cli = Client.For(YouTube.Default))
{
for (int i = 0; i < queries.Length; i++)
{
string query = queries[i];
var video = cli.GetVideo(query);
string uri = video.Uri;
string otherUri = DownloadUrlResolver
.GetDownloadUrls(query).First()
.DownloadUrl;
}
}
}
}
}
``` |
8466d262-6a42-4bf4-92eb-25b313474f0c | {
"language": "C#"
} | ```c#
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Security.Principal;
using System.ServiceModel;
namespace Microsoft.ApplicationInsights.Wcf.Tests
{
[TestClass]
public class UserTelemetryInitializerTests
{
[TestMethod]
public void AnonymousDoesNotIncludeUserId()
{
var context = new MockOperationContext();
context.EndpointUri = new Uri("http://localhost/Service1.svc");
context.OperationName = "GetData";
var authContext = new SimpleAuthorizationContext();
context.SecurityContext = new ServiceSecurityContext(authContext);
var initializer = new UserTelemetryInitializer();
var telemetry = new RequestTelemetry();
initializer.Initialize(telemetry, context);
Assert.IsNull(telemetry.Context.User.Id);
}
[TestMethod]
public void AuthenticatedRequestFillsUserIdWithUserName()
{
var context = new MockOperationContext();
context.EndpointUri = new Uri("http://localhost/Service1.svc");
context.OperationName = "GetData";
var authContext = new SimpleAuthorizationContext();
authContext.AddIdentity(new GenericIdentity("myuser"));
context.SecurityContext = new ServiceSecurityContext(authContext);
var initializer = new UserTelemetryInitializer();
var telemetry = new RequestTelemetry();
initializer.Initialize(telemetry, context);
Assert.AreEqual("myuser", telemetry.Context.User.Id);
}
}
}
```
Add test ensuring that user id is copied from request if present | ```c#
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Security.Principal;
using System.ServiceModel;
namespace Microsoft.ApplicationInsights.Wcf.Tests
{
[TestClass]
public class UserTelemetryInitializerTests
{
[TestMethod]
public void AnonymousDoesNotIncludeUserId()
{
var context = new MockOperationContext();
context.EndpointUri = new Uri("http://localhost/Service1.svc");
context.OperationName = "GetData";
var authContext = new SimpleAuthorizationContext();
context.SecurityContext = new ServiceSecurityContext(authContext);
var initializer = new UserTelemetryInitializer();
var telemetry = new RequestTelemetry();
initializer.Initialize(telemetry, context);
Assert.IsNull(telemetry.Context.User.Id);
}
[TestMethod]
public void AuthenticatedRequestFillsUserIdWithUserName()
{
var context = new MockOperationContext();
context.EndpointUri = new Uri("http://localhost/Service1.svc");
context.OperationName = "GetData";
var authContext = new SimpleAuthorizationContext();
authContext.AddIdentity(new GenericIdentity("myuser"));
context.SecurityContext = new ServiceSecurityContext(authContext);
var initializer = new UserTelemetryInitializer();
var telemetry = new RequestTelemetry();
initializer.Initialize(telemetry, context);
Assert.AreEqual("myuser", telemetry.Context.User.Id);
}
[TestMethod]
public void UserIdCopiedFromRequestIfPresent()
{
const String userName = "MyUserName";
var context = new MockOperationContext();
context.EndpointUri = new Uri("http://localhost/Service1.svc");
context.OperationName = "GetData";
context.Request.Context.User.Id = userName;
var initializer = new UserTelemetryInitializer();
var telemetry = new EventTelemetry();
initializer.Initialize(telemetry, context);
Assert.AreEqual(userName, telemetry.Context.User.Id);
}
}
}
``` |
ec838308-1c36-46e3-915c-042bdb25b657 | {
"language": "C#"
} | ```c#
using Azure.Test.PerfStress;
using CommandLine;
namespace Azure.Storage.Blobs.PerfStress.Core
{
public class CountOptions : PerfStressOptions
{
[Option('c', "count", Default = 100, HelpText = "Number of blobs")]
public int Count { get; set; }
}
}
```
Increase default count to 500 | ```c#
using Azure.Test.PerfStress;
using CommandLine;
namespace Azure.Storage.Blobs.PerfStress.Core
{
public class CountOptions : PerfStressOptions
{
[Option('c', "count", Default = 500, HelpText = "Number of blobs")]
public int Count { get; set; }
}
}
``` |
e4b3080f-6ec0-45c6-a613-9d2739a93b54 | {
"language": "C#"
} | ```c#
namespace AzureBot.Forms
{
using System;
using System.Collections.Generic;
using System.Linq;
using Azure.Management.Models;
[Serializable]
public class VirtualMachineFormState
{
public VirtualMachineFormState(IEnumerable<VirtualMachine> availableVMs, Operations operation)
{
this.AvailableVMs = availableVMs;
this.Operation = operation;
}
public string VirtualMachine { get; set; }
public IEnumerable<VirtualMachine> AvailableVMs { get; private set; }
public Operations Operation { get; private set; }
public VirtualMachine SelectedVM
{
get
{
return this.AvailableVMs.Where(p => p.Name == this.VirtualMachine).SingleOrDefault();
}
}
}
}```
Use proper case for text showing the current VM operation | ```c#
namespace AzureBot.Forms
{
using System;
using System.Collections.Generic;
using System.Linq;
using Azure.Management.Models;
[Serializable]
public class VirtualMachineFormState
{
public VirtualMachineFormState(IEnumerable<VirtualMachine> availableVMs, Operations operation)
{
this.AvailableVMs = availableVMs;
this.Operation = operation.ToString().ToLower();
}
public string VirtualMachine { get; set; }
public IEnumerable<VirtualMachine> AvailableVMs { get; private set; }
public string Operation { get; private set; }
public VirtualMachine SelectedVM
{
get
{
return this.AvailableVMs.Where(p => p.Name == this.VirtualMachine).SingleOrDefault();
}
}
}
}``` |
2a4909a2-e1e0-428e-9e95-08995c0d3667 | {
"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.Platform;
using osu.Framework.Platform.Linux;
using osu.Framework.Platform.MacOS;
using osu.Framework.Platform.Windows;
using System;
namespace osu.Framework
{
public static class Host
{
[Obsolete("Use GetSuitableHost(HostConfig) instead.")]
public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
switch (RuntimeInfo.OS)
{
case RuntimeInfo.Platform.macOS:
return new MacOSGameHost(gameName, bindIPC, portableInstallation);
case RuntimeInfo.Platform.Linux:
return new LinuxGameHost(gameName, bindIPC, portableInstallation);
case RuntimeInfo.Platform.Windows:
return new WindowsGameHost(gameName, bindIPC, portableInstallation);
default:
throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)}).");
}
}
public static DesktopGameHost GetSuitableHost(HostConfig hostConfig)
{
return RuntimeInfo.OS switch
{
RuntimeInfo.Platform.Windows => new WindowsGameHost(hostConfig),
RuntimeInfo.Platform.Linux => new LinuxGameHost(hostConfig),
RuntimeInfo.Platform.macOS => new MacOSGameHost(hostConfig),
_ => throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)})."),
};
}
}
}
```
Fix overkill and use `switch` statement | ```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.Platform;
using osu.Framework.Platform.Linux;
using osu.Framework.Platform.MacOS;
using osu.Framework.Platform.Windows;
using System;
namespace osu.Framework
{
public static class Host
{
[Obsolete("Use GetSuitableHost(HostConfig) instead.")]
public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
switch (RuntimeInfo.OS)
{
case RuntimeInfo.Platform.macOS:
return new MacOSGameHost(gameName, bindIPC, portableInstallation);
case RuntimeInfo.Platform.Linux:
return new LinuxGameHost(gameName, bindIPC, portableInstallation);
case RuntimeInfo.Platform.Windows:
return new WindowsGameHost(gameName, bindIPC, portableInstallation);
default:
throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS}).");
}
}
public static DesktopGameHost GetSuitableHost(HostConfig hostConfig)
{
switch (RuntimeInfo.OS)
{
case RuntimeInfo.Platform.Windows:
return new WindowsGameHost(hostConfig);
case RuntimeInfo.Platform.Linux:
return new LinuxGameHost(hostConfig);
case RuntimeInfo.Platform.macOS:
return new MacOSGameHost(hostConfig);
default:
throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS}).");
};
}
}
}
``` |
0baece52-6bd4-4517-a5b2-999bc64b9c22 | {
"language": "C#"
} | ```c#
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using Abc.NCrafts.App.ViewModels;
namespace Abc.NCrafts.App.Views
{
/// <summary>
/// Interaction logic for GameView.xaml
/// </summary>
public partial class Performance2018GameView : UserControl
{
public Performance2018GameView()
{
InitializeComponent();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Focusable = true;
Keyboard.Focus(this);
}
private void OnWebBrowserLoaded(object sender, NavigationEventArgs e)
{
var script = "document.body.style.overflow ='hidden'";
var wb = (WebBrowser)sender;
wb.InvokeScript("execScript", script, "JavaScript");
}
private void HtmlHelpClick(object sender, MouseButtonEventArgs e)
{
var pagePage = (PerformanceGamePage)DataContext;
pagePage.IsHelpVisible = false;
}
private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (DataContext == null)
return;
var htmlHelpContent = ((Performance2018GamePage)DataContext).HtmlHelpContent;
_webBrowser.NavigateToString(htmlHelpContent);
}
}
}
```
Fix bug which was making the app crash when clicking outside of the spoiler form | ```c#
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using Abc.NCrafts.App.ViewModels;
namespace Abc.NCrafts.App.Views
{
/// <summary>
/// Interaction logic for GameView.xaml
/// </summary>
public partial class Performance2018GameView : UserControl
{
public Performance2018GameView()
{
InitializeComponent();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Focusable = true;
Keyboard.Focus(this);
}
private void OnWebBrowserLoaded(object sender, NavigationEventArgs e)
{
var script = "document.body.style.overflow ='hidden'";
var wb = (WebBrowser)sender;
wb.InvokeScript("execScript", script, "JavaScript");
}
private void HtmlHelpClick(object sender, MouseButtonEventArgs e)
{
var pagePage = (Performance2018GamePage)DataContext;
pagePage.IsHelpVisible = false;
}
private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (DataContext == null)
return;
var htmlHelpContent = ((Performance2018GamePage)DataContext).HtmlHelpContent;
_webBrowser.NavigateToString(htmlHelpContent);
}
}
}
``` |
c6589989-77f5-4abf-8ba9-772438bbe113 | {
"language": "C#"
} | ```c#
namespace CheckDigit
{
class Program
{
static int GetControllDigit(long number)
{
int sum = 0;
bool isOddPos = true;
while (number > 0)
{
int digit = (int)(number % 10);
if (isOddPos)
{
sum += 3 * digit;
}
else
{
sum += digit;
number /= 10;
isOddPos = !isOddPos;
}
}
int modulo = sum % 7;
return modulo;
}
static void Main(string[] args)
{
int digit = GetControllDigit(12345);
}
}
}
```
Check digit: recognize infrastructural code and domain logic | ```c#
namespace CheckDigit
{
class Program
{
static int GetControllDigit(long number)
{
int sum = 0;
bool isOddPos = true;
while (number > 0) // infrastructure
{
int digit = (int)(number % 10); // infrastructure
if (isOddPos) // domain
{
sum += 3 * digit; // 3 = parameter
}
else
{
sum += digit;
number /= 10; // infrastructure
isOddPos = !isOddPos; // domain
}
}
int modulo = sum % 7; // 7 = parameter
return modulo; // % = domain
}
static void Main(string[] args)
{
int digit = GetControllDigit(12345);
}
}
}
``` |
a1a84dd8-e6cf-4929-83e8-a72eb2be5fe4 | {
"language": "C#"
} | ```c#
using System;
using CommandLine;
using CommandLine.Text;
namespace Mugo
{
/// <summary>
/// Command line options of the game.
/// </summary>
public class CommandLineOptions
{
[Option ('m', "noBackgroundMusic",
DefaultValue = false,
HelpText = "Disables background music. It can still be enabled via the m hotkey.")]
public bool NoBackgroundMusic { get; set; }
[Option ('s', "seed",
HelpText = "Sets the seed value of the random number generator.")]
public int? Seed { get; set; }
[HelpOption ('h', "help")]
public string GetUsage ()
{
return HelpText.AutoBuild (this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler (this, current));
}
}
}
```
Use imperative in help messages. | ```c#
using System;
using CommandLine;
using CommandLine.Text;
namespace Mugo
{
/// <summary>
/// Command line options of the game.
/// </summary>
public class CommandLineOptions
{
[Option ('m', "noBackgroundMusic",
DefaultValue = false,
HelpText = "Disable background music. It can still be enabled via the m hotkey.")]
public bool NoBackgroundMusic { get; set; }
[Option ('s', "seed",
HelpText = "Set the seed value of the random number generator.")]
public int? Seed { get; set; }
[HelpOption ('h', "help")]
public string GetUsage ()
{
return HelpText.AutoBuild (this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler (this, current));
}
}
}
``` |
4801b036-35ff-45e8-bd00-508f4437c177 | {
"language": "C#"
} | ```c#
#region
using System.Windows;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
Settings.Default.Save();
ClickOnceHelper.RunOnStartup(Settings.Default.AlwaysOn);
}
}
}```
Fix unhandled error causing crash | ```c#
#region
using System.Windows;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
Settings.Default.Save();
ClickOnceHelper.RunOnStartup(Settings.Default.AlwaysOn);
}
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var errorMessage = $"An unhandled exception occurred:\n\n{e.Exception.Message}";
MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
e.Handled = true;
}
}
}``` |
be637f52-b8a8-4b5d-acf7-9071196a19d5 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using NUnit.Framework;
using SharpBrake;
using SharpBrake.Serialization;
namespace Tests
{
[TestFixture]
public class AirbrakeClientTests
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
this.client = new AirbrakeClient();
}
#endregion
private AirbrakeClient client;
[Test]
public void Send_EndRequestEventIsInvoked_And_ResponseOnlyContainsApiError()
{
bool requestEndInvoked = false;
AirbrakeResponseError[] errors = null;
int i = 0;
this.client.RequestEnd += (sender, e) =>
{
requestEndInvoked = true;
errors = e.Response.Errors;
};
var configuration = new AirbrakeConfiguration
{
ApiKey = Guid.NewGuid().ToString("N"),
EnvironmentName = "test",
};
var builder = new AirbrakeNoticeBuilder(configuration);
AirbrakeNotice notice = builder.Notice(new Exception("Test"));
notice.Request = new AirbrakeRequest("http://example.com", "Test")
{
Params = new[]
{
new AirbrakeVar("TestKey", "TestValue")
}
};
this.client.Send(notice);
while (!requestEndInvoked)
{
// Sleep for maximum 5 seconds to wait for the request to end. Can probably be done more elegantly.
if (i++ == 50)
break;
Thread.Sleep(100);
}
Assert.That(requestEndInvoked, Is.True);
Assert.That(errors, Is.Not.Null);
Assert.That(errors, Has.Length.EqualTo(1));
}
}
}```
Use the .After() method in NUnit instead of Thread.Sleep | ```c#
using System;
using NUnit.Framework;
using SharpBrake;
using SharpBrake.Serialization;
namespace Tests
{
[TestFixture]
public class AirbrakeClientTests
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
this.client = new AirbrakeClient();
}
#endregion
private AirbrakeClient client;
[Test]
public void Send_EndRequestEventIsInvoked_And_ResponseOnlyContainsApiError()
{
bool requestEndInvoked = false;
AirbrakeResponseError[] errors = null;
int i = 0;
this.client.RequestEnd += (sender, e) =>
{
requestEndInvoked = true;
errors = e.Response.Errors;
};
var configuration = new AirbrakeConfiguration
{
ApiKey = Guid.NewGuid().ToString("N"),
EnvironmentName = "test",
};
var builder = new AirbrakeNoticeBuilder(configuration);
AirbrakeNotice notice = builder.Notice(new Exception("Test"));
notice.Request = new AirbrakeRequest("http://example.com", "Test")
{
Params = new[]
{
new AirbrakeVar("TestKey", "TestValue")
}
};
this.client.Send(notice);
Assert.That(requestEndInvoked, Is.True.After(5000));
Assert.That(errors, Is.Not.Null);
Assert.That(errors, Has.Length.EqualTo(1));
}
}
}``` |
2ba6c087-8e4a-4a4e-a2d4-fd7d7c2b6aa0 | {
"language": "C#"
} | ```c#
using System;
namespace SharpCompress.Common
{
public class ReaderExtractionEventArgs<T> : EventArgs
{
internal ReaderExtractionEventArgs(T entry, params object[] paramList)
{
Item = entry;
ParamList = paramList;
}
public T Item { get; private set; }
public object[] ParamList { get; private set; }
}
}```
Use strongly typed ReaderProgress instead of object[] | ```c#
using System;
using SharpCompress.Readers;
namespace SharpCompress.Common
{
public class ReaderExtractionEventArgs<T> : EventArgs
{
internal ReaderExtractionEventArgs(T entry, ReaderProgress readerProgress = null)
{
Item = entry;
ReaderProgress = readerProgress;
}
public T Item { get; private set; }
public ReaderProgress ReaderProgress { get; private set; }
}
}``` |
8aa3df62-8bf0-4b43-886a-be7e57e218cb | {
"language": "C#"
} | ```c#
using System.Net;
using System.Net.Sockets;
namespace Tgstation.Server.Host.Extensions
{
/// <summary>
/// Extension methods for the <see cref="Socket"/> <see langword="class"/>.
/// </summary>
static class SocketExtensions
{
/// <summary>
/// Attempt to exclusively bind to a given <paramref name="port"/>.
/// </summary>
/// <param name="port">The port number to bind to.</param>
/// <param name="includeIPv6">If IPV6 should be tested as well.</param>
public static void BindTest(ushort port, bool includeIPv6)
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
if (includeIPv6)
socket.DualMode = true;
socket.Bind(
new IPEndPoint(
includeIPv6
? IPAddress.IPv6Any
: IPAddress.Any,
port));
}
}
}
```
Fix IPV6 issue with BindTest | ```c#
using System.Net;
using System.Net.Sockets;
namespace Tgstation.Server.Host.Extensions
{
/// <summary>
/// Extension methods for the <see cref="Socket"/> <see langword="class"/>.
/// </summary>
static class SocketExtensions
{
/// <summary>
/// Attempt to exclusively bind to a given <paramref name="port"/>.
/// </summary>
/// <param name="port">The port number to bind to.</param>
/// <param name="includeIPv6">If IPV6 should be tested as well.</param>
public static void BindTest(ushort port, bool includeIPv6)
{
using var socket = new Socket(
includeIPv6
? AddressFamily.InterNetworkV6
: AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
if (includeIPv6)
socket.DualMode = true;
socket.Bind(
new IPEndPoint(
includeIPv6
? IPAddress.IPv6Any
: IPAddress.Any,
port));
}
}
}
``` |
d63d920b-b43b-458c-884c-36c251a0047f | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using FluentAssertions;
using Xunit;
namespace Okanshi.Test
{
public class PerformanceCounterTest
{
[Fact]
public void Performance_counter_without_instance_name()
{
var performanceCounter = new PerformanceCounter("Memory", "Available Bytes");
var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"),
PerformanceCounterConfig.Build("Memory", "Available Bytes"));
monitor.GetValue()
.Should()
.BeGreaterThan(0)
.And.BeApproximately(performanceCounter.NextValue(), 100000,
"Because memory usage can change between the two values");
}
[Fact]
public void Performance_counter_with_instance_name()
{
var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName);
var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"),
PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName));
monitor.GetValue()
.Should()
.BeGreaterThan(0)
.And.BeApproximately(performanceCounter.NextValue(), 100000,
"Because memory usage can change between the two values");
}
}
}
```
Improve performance counter test stability | ```c#
using System.Diagnostics;
using FluentAssertions;
using Xunit;
namespace Okanshi.Test
{
public class PerformanceCounterTest
{
[Fact]
public void Performance_counter_without_instance_name()
{
var performanceCounter = new PerformanceCounter("Memory", "Available Bytes");
var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"),
PerformanceCounterConfig.Build("Memory", "Available Bytes"));
monitor.GetValue()
.Should()
.BeGreaterThan(0)
.And.BeApproximately(performanceCounter.NextValue(), 500000,
"Because memory usage can change between the two values");
}
[Fact]
public void Performance_counter_with_instance_name()
{
var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName);
var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"),
PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName));
monitor.GetValue()
.Should()
.BeGreaterThan(0)
.And.BeApproximately(performanceCounter.NextValue(), 500000,
"Because memory usage can change between the two values");
}
}
}
``` |
d3aad874-0202-409a-aa05-05336b9d4d27 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace HarSharp
{
/// <summary>
/// A base class for HTTP messages.
/// </summary>
public abstract class MessageBase : EntityBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MessageBase"/> class.
/// </summary>
protected MessageBase()
{
Cookies = new List<Cookie>();
Headers = new List<Header>();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the HTTP Version.
/// </summary>
public string HttpVersion { get; set; }
/// <summary>
/// Gets the list of cookie objects.
/// </summary>
public IList<Cookie> Cookies { get; private set; }
/// <summary>
/// Gets the list of header objects.
/// </summary>
public IList<Header> Headers { get; private set; }
/// <summary>
/// Gets or sets the total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body.
/// </summary>
public int HeadersSize { get; set; }
/// <summary>
/// Gets or sets the size of the request body (POST data payload) in bytes.
/// </summary>
public int BodySize { get; set; }
#endregion
}
}
```
Fix error when deserializing response with BodySize set to null (tested with HAR file exported with Firefox). | ```c#
using System.Collections.Generic;
namespace HarSharp
{
/// <summary>
/// A base class for HTTP messages.
/// </summary>
public abstract class MessageBase : EntityBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MessageBase"/> class.
/// </summary>
protected MessageBase()
{
Cookies = new List<Cookie>();
Headers = new List<Header>();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the HTTP Version.
/// </summary>
public string HttpVersion { get; set; }
/// <summary>
/// Gets the list of cookie objects.
/// </summary>
public IList<Cookie> Cookies { get; private set; }
/// <summary>
/// Gets the list of header objects.
/// </summary>
public IList<Header> Headers { get; private set; }
/// <summary>
/// Gets or sets the total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body.
/// </summary>
public int HeadersSize { get; set; }
/// <summary>
/// Gets or sets the size of the request body (POST data payload) in bytes.
/// </summary>
public int? BodySize { get; set; }
#endregion
}
}
``` |
8d42c315-f289-4410-a412-1b86bd7ecf72 | {
"language": "C#"
} | ```c#
Order: 30
Title: Visual Studio
Description: Extensions and supported features for Visual Studio
RedirectFrom: docs/editors/visualstudio
---
<p>
The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio </a>
brings the following features to Visual Studio:
<ul>
<li>Language support for Cake build scripts</li>
<li><a href="/docs/integrations/editors/visualstudio/templates">Templates</a></li>
<li><a href="/docs/integrations/editors/visualstudio/commands">Commands</a> for working with Cake files</li>
<li><a href="/docs/integrations/editors/visualstudio/snippets">Snippets</a></li>
<li><a href="/docs/integrations/editors/visualstudio/task-runner">Integration with Task Runner Explorer</a></li>
</ul>
</p>
<h1>Installation & configuration</h1>
See <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> for instructions how to install and configure the extension.
<h1>Child pages</h1>
@Html.Partial("_ChildPages")```
Add note about supported Visual Studio versions | ```c#
Order: 30
Title: Visual Studio
Description: Extensions and supported features for Visual Studio
RedirectFrom: docs/editors/visualstudio
---
<p>
The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio </a>
brings the following features to Visual Studio:
<ul>
<li>Language support for Cake build scripts</li>
<li><a href="/docs/integrations/editors/visualstudio/templates">Templates</a></li>
<li><a href="/docs/integrations/editors/visualstudio/commands">Commands</a> for working with Cake files</li>
<li><a href="/docs/integrations/editors/visualstudio/snippets">Snippets</a></li>
<li><a href="/docs/integrations/editors/visualstudio/task-runner">Integration with Task Runner Explorer</a></li>
</ul>
</p>
<h1>Installation & configuration</h1>
<p>
See <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> for instructions how to install and configure the extension.
</p>
<div class="alert alert-info">
<p>
The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> supports Visual Studio 2017 and newer.
</p>
</div>
<h1>Child pages</h1>
@Html.Partial("_ChildPages")``` |
87c6df26-0630-45b8-85fe-42fcf7524357 | {
"language": "C#"
} | ```c#
// SqliteNote.cs created with MonoDevelop
// User: calvin at 10:56 AM 2/12/2008
//
// To change standard headers go to Edit->Preferences->Coding->Standard Headers
//
namespace Tasque.Backends.Sqlite
{
public class SqliteNote : TaskNote
{
private int id;
private string text;
public SqliteNote (int id, string text)
{
this.id = id;
this.text = text;
}
public string Text {
get { return this.text; }
set { this.text = value; }
}
public int ID {
get { return this.id; }
}
}
}
```
Adjust to new model. Provide change callback for task. | ```c#
// SqliteNote.cs created with MonoDevelop
// User: calvin at 10:56 AM 2/12/2008
//
// To change standard headers go to Edit->Preferences->Coding->Standard Headers
//
using System;
namespace Tasque.Backends.Sqlite
{
public class SqliteNote : TaskNote
{
public SqliteNote (int id, string text) : base (text)
{
Id = id;
}
public int Id { get; private set; }
protected override void OnTextChanged ()
{
if (OnTextChangedAction != null)
OnTextChangedAction ();
base.OnTextChanged ();
}
internal Action OnTextChangedAction { get; set; }
}
}
``` |
896c1154-dcdb-4c90-a723-df9fd5d3bd62 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using System.Runtime.Versioning;
namespace NuGet.Lucene
{
public class FastZipPackageFile : IPackageFile
{
private readonly IFastZipPackage fastZipPackage;
private readonly FrameworkName targetFramework;
internal FastZipPackageFile(IFastZipPackage fastZipPackage, string path)
{
this.fastZipPackage = fastZipPackage;
Path = path;
string effectivePath;
targetFramework = VersionUtility.ParseFrameworkNameFromFilePath(Normalize(path), out effectivePath);
EffectivePath = effectivePath;
}
private string Normalize(string path)
{
return path
.Replace('/', System.IO.Path.DirectorySeparatorChar)
.TrimStart(System.IO.Path.DirectorySeparatorChar);
}
public string Path
{
get;
private set;
}
public string EffectivePath
{
get;
private set;
}
public FrameworkName TargetFramework
{
get
{
return targetFramework;
}
}
IEnumerable<FrameworkName> IFrameworkTargetable.SupportedFrameworks
{
get
{
if (TargetFramework != null)
{
yield return TargetFramework;
}
}
}
public Stream GetStream()
{
return fastZipPackage.GetZipEntryStream(Path);
}
public override string ToString()
{
return Path;
}
}
}
```
Normalize path so NuGet.Core's GetFiles(path) works correctly. | ```c#
using System.Collections.Generic;
using System.IO;
using System.Runtime.Versioning;
namespace NuGet.Lucene
{
public class FastZipPackageFile : IPackageFile
{
private readonly IFastZipPackage fastZipPackage;
private readonly FrameworkName targetFramework;
internal FastZipPackageFile(IFastZipPackage fastZipPackage, string path)
{
this.fastZipPackage = fastZipPackage;
Path = Normalize(path);
string effectivePath;
targetFramework = VersionUtility.ParseFrameworkNameFromFilePath(Path, out effectivePath);
EffectivePath = effectivePath;
}
private string Normalize(string path)
{
return path
.Replace('/', System.IO.Path.DirectorySeparatorChar)
.TrimStart(System.IO.Path.DirectorySeparatorChar);
}
public string Path
{
get;
private set;
}
public string EffectivePath
{
get;
private set;
}
public FrameworkName TargetFramework
{
get
{
return targetFramework;
}
}
IEnumerable<FrameworkName> IFrameworkTargetable.SupportedFrameworks
{
get
{
if (TargetFramework != null)
{
yield return TargetFramework;
}
}
}
public Stream GetStream()
{
return fastZipPackage.GetZipEntryStream(Path);
}
public override string ToString()
{
return Path;
}
}
}
``` |
2fed78d4-055e-424c-91c0-fb7d56d8e999 | {
"language": "C#"
} | ```c#
namespace GitVersion
{
using System.IO;
using System.Linq;
using GitVersion.VersionCalculation;
using LibGit2Sharp;
public class GitVersionFinder
{
public SemanticVersion FindVersion(GitVersionContext context)
{
Logger.WriteInfo(string.Format("Running against branch: {0} ({1})", context.CurrentBranch.Name, context.CurrentCommit.Sha));
EnsureMainTopologyConstraints(context);
var filePath = Path.Combine(context.Repository.GetRepositoryDirectory(), "NextVersion.txt");
if (File.Exists(filePath))
{
throw new WarningException("NextVersion.txt has been depreciated. See http://gitversion.readthedocs.org/en/latest/configuration/ for replacement");
}
return new NextVersionCalculator().FindVersion(context);
}
void EnsureMainTopologyConstraints(GitVersionContext context)
{
EnsureLocalBranchExists(context.Repository, "master");
EnsureHeadIsNotDetached(context);
}
void EnsureHeadIsNotDetached(GitVersionContext context)
{
if (!context.CurrentBranch.IsDetachedHead())
{
return;
}
var message = string.Format(
"It looks like the branch being examined is a detached Head pointing to commit '{0}'. " +
"Without a proper branch name GitVersion cannot determine the build version.",
context.CurrentCommit.Id.ToString(7));
throw new WarningException(message);
}
void EnsureLocalBranchExists(IRepository repository, string branchName)
{
if (repository.FindBranch(branchName) != null)
{
return;
}
var existingBranches = string.Format("'{0}'", string.Join("', '", repository.Branches.Select(x => x.CanonicalName)));
throw new WarningException(string.Format("This repository doesn't contain a branch named '{0}'. Please create one. Existing branches: {1}", branchName, existingBranches));
}
}
}```
Remove requirement on master branch existing | ```c#
namespace GitVersion
{
using System.IO;
using System.Linq;
using GitVersion.VersionCalculation;
using LibGit2Sharp;
public class GitVersionFinder
{
public SemanticVersion FindVersion(GitVersionContext context)
{
Logger.WriteInfo(string.Format("Running against branch: {0} ({1})", context.CurrentBranch.Name, context.CurrentCommit.Sha));
EnsureMainTopologyConstraints(context);
var filePath = Path.Combine(context.Repository.GetRepositoryDirectory(), "NextVersion.txt");
if (File.Exists(filePath))
{
throw new WarningException("NextVersion.txt has been depreciated. See http://gitversion.readthedocs.org/en/latest/configuration/ for replacement");
}
return new NextVersionCalculator().FindVersion(context);
}
void EnsureMainTopologyConstraints(GitVersionContext context)
{
EnsureHeadIsNotDetached(context);
}
void EnsureHeadIsNotDetached(GitVersionContext context)
{
if (!context.CurrentBranch.IsDetachedHead())
{
return;
}
var message = string.Format(
"It looks like the branch being examined is a detached Head pointing to commit '{0}'. " +
"Without a proper branch name GitVersion cannot determine the build version.",
context.CurrentCommit.Id.ToString(7));
throw new WarningException(message);
}
}
}``` |
29e38f64-001c-4ef6-8229-02fc939d290b | {
"language": "C#"
} | ```c#
namespace Mages.Repl.Functions
{
using System;
sealed class ReplObject
{
public String Read()
{
return Console.ReadLine();
}
public void Write(String str)
{
Console.Write(str);
}
public void WriteLine(String str)
{
Console.WriteLine(str);
}
}
}
```
Write arbitrary content to the repl | ```c#
namespace Mages.Repl.Functions
{
using Mages.Core.Runtime;
using System;
sealed class ReplObject
{
public String Read()
{
return Console.ReadLine();
}
public void Write(Object value)
{
var str = Stringify.This(value);
Console.Write(str);
}
public void WriteLine(Object value)
{
var str = Stringify.This(value);
Console.WriteLine(str);
}
}
}
``` |
fabe1862-3fed-451a-994f-ea4f554539e9 | {
"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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Abp.Quartz")]
[assembly: AssemblyTrademark("")]
// 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("f90b1606-f375-4c84-9118-ab0c1ddeb0df")]
```
Change assemblyinfo for quartz package. | ```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("Abp.Quartz")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Volosoft")]
[assembly: AssemblyProduct("Abp.Quartz")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("f90b1606-f375-4c84-9118-ab0c1ddeb0df")]
``` |
5e87dfd0-0864-4d6b-9539-bafab752eee8 | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using RoundedBoxView.Forms.Plugin.iOSUnified;
using RoundedBoxView.Forms.Plugin.iOSUnified.ExtensionMethods;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly:
ExportRenderer(typeof (RoundedBoxView.Forms.Plugin.Abstractions.RoundedBoxView), typeof (RoundedBoxViewRenderer))]
namespace RoundedBoxView.Forms.Plugin.iOSUnified
{
/// <summary>
/// Source From : https://gist.github.com/rudyryk/8cbe067a1363b45351f6
/// </summary>
public class RoundedBoxViewRenderer : BoxRenderer
{
/// <summary>
/// Used for registration with dependency service
/// </summary>
public static void Init()
{
}
private Abstractions.RoundedBoxView _formControl
{
get { return Element as Abstractions.RoundedBoxView; }
}
protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
{
base.OnElementChanged(e);
this.InitializeFrom(_formControl);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
this.UpdateFrom(_formControl, e.PropertyName);
}
}
}
```
Fix for link sdk assemblies only on iOS | ```c#
using System.ComponentModel;
using RoundedBoxView.Forms.Plugin.iOSUnified;
using RoundedBoxView.Forms.Plugin.iOSUnified.ExtensionMethods;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using Foundation;
using System;
[assembly:
ExportRenderer(typeof (RoundedBoxView.Forms.Plugin.Abstractions.RoundedBoxView), typeof (RoundedBoxViewRenderer))]
namespace RoundedBoxView.Forms.Plugin.iOSUnified
{
/// <summary>
/// Source From : https://gist.github.com/rudyryk/8cbe067a1363b45351f6
/// </summary>
[Preserve(AllMembers = true)]
public class RoundedBoxViewRenderer : BoxRenderer
{
/// <summary>
/// Used for registration with dependency service
/// </summary>
public static void Init()
{
var temp = DateTime.Now;
}
private Abstractions.RoundedBoxView _formControl
{
get { return Element as Abstractions.RoundedBoxView; }
}
protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
{
base.OnElementChanged(e);
this.InitializeFrom(_formControl);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
this.UpdateFrom(_formControl, e.PropertyName);
}
}
}
``` |
fce2e357-4d27-4332-80fe-376c019a64af | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
namespace osu.Framework.IO.Stores
{
public class NamespacedResourceStore<T> : ResourceStore<T>
where T : class
{
public string Namespace;
/// <summary>
/// Initializes a resource store with a single store.
/// </summary>
/// <param name="store">The store.</param>
/// <param name="ns">The namespace to add.</param>
public NamespacedResourceStore(IResourceStore<T> store, string ns)
: base(store)
{
Namespace = ns;
}
protected override IEnumerable<string> GetFilenames(string name) => base.GetFilenames($@"{Namespace}/{name}");
public override IEnumerable<string> GetAvailableResources() => base.GetAvailableResources()
.Where(x => x.StartsWith($"{Namespace}/"))
.Select(x => x.Remove(0, $"{Namespace}/".Length));
}
}
```
Replace a string.Remove with slicing. | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
namespace osu.Framework.IO.Stores
{
public class NamespacedResourceStore<T> : ResourceStore<T>
where T : class
{
public string Namespace;
/// <summary>
/// Initializes a resource store with a single store.
/// </summary>
/// <param name="store">The store.</param>
/// <param name="ns">The namespace to add.</param>
public NamespacedResourceStore(IResourceStore<T> store, string ns)
: base(store)
{
Namespace = ns;
}
protected override IEnumerable<string> GetFilenames(string name) => base.GetFilenames($@"{Namespace}/{name}");
public override IEnumerable<string> GetAvailableResources() => base.GetAvailableResources()
.Where(x => x.StartsWith($"{Namespace}/"))
.Select(x => x[(Namespace.Length + 1)..]);
}
}
``` |
995373f5-2828-46f0-9957-027f4b9478f9 | {
"language": "C#"
} | ```c#
using System;
using System.Text;
using DbUp.Support;
namespace DbUp.MySql
{
/// <summary>
/// Reads MySQL commands from an underlying text stream. Supports DELIMITED .. statement
/// </summary>
public class MySqlCommandReader : SqlCommandReader
{
const string DelimiterKeyword = "DELIMITER";
/// <summary>
/// Creates an instance of MySqlCommandReader
/// </summary>
public MySqlCommandReader(string sqlText) : base(sqlText, ";", delimiterRequiresWhitespace: false)
{
}
/// <summary>
/// Hook to support custom statements
/// </summary>
protected override bool IsCustomStatement => TryPeek(DelimiterKeyword.Length - 1, out var statement) &&
string.Equals(DelimiterKeyword, CurrentChar + statement, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Read a custom statement
/// </summary>
protected override void ReadCustomStatement()
{
// Move past Delimiter keyword
var count = DelimiterKeyword.Length + 1;
Read(new char[count], 0, count);
SkipWhitespace();
// Read until we hit the end of line.
var delimiter = new StringBuilder();
do
{
delimiter.Append(CurrentChar);
if (Read() == FailedRead)
{
break;
}
}
while (!IsEndOfLine && !IsWhiteSpace);
Delimiter = delimiter.ToString();
}
void SkipWhitespace()
{
while (char.IsWhiteSpace(CurrentChar))
{
Read();
}
}
}
}```
Fix potential infinite loop in SkipWhitespace | ```c#
using System;
using System.Text;
using DbUp.Support;
namespace DbUp.MySql
{
/// <summary>
/// Reads MySQL commands from an underlying text stream. Supports DELIMITED .. statement
/// </summary>
public class MySqlCommandReader : SqlCommandReader
{
const string DelimiterKeyword = "DELIMITER";
/// <summary>
/// Creates an instance of MySqlCommandReader
/// </summary>
public MySqlCommandReader(string sqlText) : base(sqlText, ";", delimiterRequiresWhitespace: false)
{
}
/// <summary>
/// Hook to support custom statements
/// </summary>
protected override bool IsCustomStatement => TryPeek(DelimiterKeyword.Length - 1, out var statement) &&
string.Equals(DelimiterKeyword, CurrentChar + statement, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Read a custom statement
/// </summary>
protected override void ReadCustomStatement()
{
// Move past Delimiter keyword
var count = DelimiterKeyword.Length + 1;
Read(new char[count], 0, count);
SkipWhitespace();
// Read until we hit the end of line.
var delimiter = new StringBuilder();
do
{
delimiter.Append(CurrentChar);
if (Read() == FailedRead)
{
break;
}
}
while (!IsEndOfLine && !IsWhiteSpace);
Delimiter = delimiter.ToString();
}
void SkipWhitespace()
{
int result;
do
{
result = Read();
} while (result != FailedRead && char.IsWhiteSpace(CurrentChar));
}
}
}
``` |
9d04922f-d625-4455-8d4d-2c942140f8fa | {
"language": "C#"
} | ```c#
using System;
namespace FTF.Core.Notes
{
public class CreateNote
{
private readonly Func<int> _generateId;
private readonly Func<DateTime> _getCurrentDate;
private readonly Action<Note> _saveNote;
private readonly Action _saveChanges;
public CreateNote(Func<int> generateId, Func<DateTime> getCurrentDate, Action<Note> saveNote, Action saveChanges)
{
_generateId = generateId;
_getCurrentDate = getCurrentDate;
_saveNote = saveNote;
_saveChanges = saveChanges;
}
public void Create(int id, string text)
{
_saveNote(new Note
{
Id = _generateId(),
Text = text,
CreationDate = _getCurrentDate()
});
_saveChanges();
}
}
}```
Implement fake tag parser to test integration | ```c#
using System;
using System.Collections.Generic;
namespace FTF.Core.Notes
{
public class CreateNote
{
private readonly Func<int> _generateId;
private readonly Func<DateTime> _getCurrentDate;
private readonly Action<Note> _saveNote;
private readonly Action _saveChanges;
public CreateNote(Func<int> generateId, Func<DateTime> getCurrentDate, Action<Note> saveNote, Action saveChanges)
{
_generateId = generateId;
_getCurrentDate = getCurrentDate;
_saveNote = saveNote;
_saveChanges = saveChanges;
}
public void Create(int id, string text)
{
_saveNote(new Note
{
Id = _generateId(),
Text = text,
CreationDate = _getCurrentDate(),
Tags = ParseTags(text)
});
_saveChanges();
}
private ICollection<Tag> ParseTags(string text) => new List<Tag> { new Tag { Name = "Buy"} };
}
}``` |
96dc0cc2-ce78-422c-b72b-c6cb5938fe12 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AgateLib;
using AgateLib.Drivers;
using AgateLib.DisplayLib;
namespace AgateLib.UnitTests.DisplayTest
{
[TestClass]
public class DisplayTest
{
[TestMethod]
public void InitializeDisplay()
{
using (AgateSetup setup = new AgateSetup())
{
setup.PreferredDisplay = (DisplayTypeID) 1000;
setup.InitializeDisplay((DisplayTypeID)1000);
Assert.IsFalse(setup.WasCanceled);
DisplayWindow wind = DisplayWindow.CreateWindowed("Title", 400, 400);
}
}
}
}
```
Disable display test that is failing in CI build. | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AgateLib;
using AgateLib.Drivers;
using AgateLib.DisplayLib;
namespace AgateLib.UnitTests.DisplayTest
{
[TestClass]
public class DisplayTest
{
/*
[TestMethod]
public void InitializeDisplay()
{
using (AgateSetup setup = new AgateSetup())
{
setup.PreferredDisplay = (DisplayTypeID) 1000;
setup.InitializeDisplay((DisplayTypeID)1000);
Assert.IsFalse(setup.WasCanceled);
DisplayWindow wind = DisplayWindow.CreateWindowed("Title", 400, 400);
}
}
* */
}
}
``` |
13debc46-1b3b-45c6-b862-8590eecd8556 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using UELib;
using UELib.Core;
namespace UELib.Core
{
public partial class UTextBuffer : UObject
{
public override string Decompile()
{
if( _bDeserializeOnDemand )
{
BeginDeserializing();
}
if( ScriptText.Length != 0 )
{
if( Outer is UStruct )
{
try
{
return ScriptText + ((UClass)Outer).FormatDefaultProperties();
}
catch
{
return ScriptText + "\r\n// Failed to decompile defaultproperties for this object.";
}
}
return ScriptText;
}
return "TextBuffer is empty!";
}
}
}
```
Add a comment for exported DefaultProperties. | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using UELib;
using UELib.Core;
namespace UELib.Core
{
public partial class UTextBuffer : UObject
{
public override string Decompile()
{
if( _bDeserializeOnDemand )
{
BeginDeserializing();
}
if( ScriptText.Length != 0 )
{
if( Outer is UStruct )
{
try
{
return ScriptText
+ (((UClass)Outer).Properties != null && ((UClass)Outer).Properties.Count > 0 ? "// Decompiled with UE Explorer." : "// No DefaultProperties.")
+ ((UClass)Outer).FormatDefaultProperties();
}
catch
{
return ScriptText + "\r\n// Failed to decompile defaultproperties for this object.";
}
}
return ScriptText;
}
return "TextBuffer is empty!";
}
}
}``` |
c1836915-0fdc-4ad8-934d-bd14277d7631 | {
"language": "C#"
} | ```c#
// Copyright © 2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Threading.Tasks;
using CefSharp.WinForms;
using Xunit;
using Xunit.Abstractions;
namespace CefSharp.Test.WinForms
{
//NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle
[Collection(CefSharpFixtureCollection.Key)]
public class WinFormsBrowserBasicFacts
{
private readonly ITestOutputHelper output;
private readonly CefSharpFixture fixture;
public WinFormsBrowserBasicFacts(ITestOutputHelper output, CefSharpFixture fixture)
{
this.fixture = fixture;
this.output = output;
}
[WinFormsFact]
public async Task CanLoadGoogle()
{
using (var browser = new ChromiumWebBrowser("www.google.com"))
{
var form = new System.Windows.Forms.Form();
form.Controls.Add(browser);
form.Show();
await browser.LoadPageAsync();
var mainFrame = browser.GetMainFrame();
Assert.True(mainFrame.IsValid);
Assert.True(mainFrame.Url.Contains("www.google"));
output.WriteLine("Url {0}", mainFrame.Url);
}
}
}
}
```
Test - Avoid displaying Form in WinForms Test | ```c#
// Copyright © 2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Threading.Tasks;
using CefSharp.WinForms;
using Xunit;
using Xunit.Abstractions;
namespace CefSharp.Test.WinForms
{
//NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle
[Collection(CefSharpFixtureCollection.Key)]
public class WinFormsBrowserBasicFacts
{
private readonly ITestOutputHelper output;
private readonly CefSharpFixture fixture;
public WinFormsBrowserBasicFacts(ITestOutputHelper output, CefSharpFixture fixture)
{
this.fixture = fixture;
this.output = output;
}
[WinFormsFact]
public async Task CanLoadGoogle()
{
using (var browser = new ChromiumWebBrowser("www.google.com"))
{
browser.Size = new System.Drawing.Size(1024, 768);
browser.CreateControl();
await browser.LoadPageAsync();
var mainFrame = browser.GetMainFrame();
Assert.True(mainFrame.IsValid);
Assert.True(mainFrame.Url.Contains("www.google"));
output.WriteLine("Url {0}", mainFrame.Url);
}
}
}
}
``` |
59855456-b50b-4f74-a0ee-ea552b57eece | {
"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;
}
}
}
}
```
Update english to be more readable | ```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:
text.Text = @"No scores have been set yet. Maybe you can be the first!";
return;
case BeatmapLeaderboardScope.Friend:
text.Text = @"None of your friends have 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;
}
}
}
}
``` |
7fecc285-fad2-40a4-91eb-d7893a72f625 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
namespace LearnositySDK
{
public static class Credentials
{
public static string ConsumerKey = "yis0TYCu7U9V4o7M";
public static string ConsumerSecret = "74c5fd430cf1242a527f6223aebd42d30464be22";
public static string Domain = "localhost";
}
}
```
Add passwords-in-version-control disclaimer to credentials file. | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
namespace LearnositySDK
{
public static class Credentials
{
// The consumerKey and consumerSecret are the public & private
// security keys required to access Learnosity APIs and
// data. Learnosity will provide keys for your own private account.
// Note: The consumer secret should be in a properly secured credential
// store, and *NEVER* checked into version control.
// The keys listed here grant access to Learnosity's public demos account.
public static string ConsumerKey = "yis0TYCu7U9V4o7M";
public static string ConsumerSecret = "74c5fd430cf1242a527f6223aebd42d30464be22";
public static string Domain = "localhost";
}
}
``` |
ac16988a-0b76-442c-8873-44eb271434b5 | {
"language": "C#"
} | ```c#
using System;
namespace Satrabel.OpenContent.Components.TemplateHelpers
{
public class Ratio
{
private readonly float _ratio;
public int Width { get; private set; }
public int Height { get; private set; }
public float AsFloat
{
get { return Width / Height; }
}
public Ratio(string ratioString)
{
Width = 1;
Height = 1;
var elements = ratioString.ToLowerInvariant().Split('x');
if (elements.Length == 2)
{
int leftPart;
int rightPart;
if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
{
Width = leftPart;
Height = rightPart;
}
}
_ratio = AsFloat;
}
public Ratio(int width, int height)
{
if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
Width = width;
Height = height;
_ratio = AsFloat;
}
public void SetWidth(int newWidth)
{
Width = newWidth;
Height = Convert.ToInt32(newWidth / _ratio);
}
public void SetHeight(int newHeight)
{
Width = Convert.ToInt32(newHeight * _ratio);
Height = newHeight;
}
}
}```
Fix issue where ratio was always returning "1" | ```c#
using System;
namespace Satrabel.OpenContent.Components.TemplateHelpers
{
public class Ratio
{
private readonly float _ratio;
public int Width { get; private set; }
public int Height { get; private set; }
public float AsFloat
{
get { return (float)Width / (float)Height); }
}
public Ratio(string ratioString)
{
Width = 1;
Height = 1;
var elements = ratioString.ToLowerInvariant().Split('x');
if (elements.Length == 2)
{
int leftPart;
int rightPart;
if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
{
Width = leftPart;
Height = rightPart;
}
}
_ratio = AsFloat;
}
public Ratio(int width, int height)
{
if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
Width = width;
Height = height;
_ratio = AsFloat;
}
public void SetWidth(int newWidth)
{
Width = newWidth;
Height = Convert.ToInt32(newWidth / _ratio);
}
public void SetHeight(int newHeight)
{
Width = Convert.ToInt32(newHeight * _ratio);
Height = newHeight;
}
}
}``` |
be0c19c4-9f20-4e69-a82f-7dda23162a29 | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace OctopusPuppet.DeploymentPlanner
{
public class SemVerJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var version = token.ToString();
return new SemVer(version);
}
public override bool CanConvert(Type objectType)
{
return typeof(SemVer).IsAssignableFrom(objectType);
}
}
}
```
Allow empty semver components to be deserialised as this might be an archived component | ```c#
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace OctopusPuppet.DeploymentPlanner
{
public class SemVerJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var version = token.ToString();
if (string.IsNullOrEmpty(version))
return null;
return new SemVer(version);
}
public override bool CanConvert(Type objectType)
{
return typeof(SemVer).IsAssignableFrom(objectType);
}
}
}
``` |
22082f22-467e-4c66-9d4c-e24ecd2dc715 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class PullRequestFile
{
public PullRequestFile() { }
public PullRequestFile(string sha, string fileName, string status, int additions, int deletions, int changes, Uri blobUri, Uri rawUri, Uri contentsUri, string patch)
{
Sha = sha;
FileName = fileName;
Status = status;
Additions = additions;
Deletions = deletions;
Changes = changes;
BlobUri = blobUri;
RawUri = rawUri;
ContentsUri = contentsUri;
Patch = patch;
}
public string Sha { get; protected set; }
public string FileName { get; protected set; }
public string Status { get; protected set; }
public int Additions { get; protected set; }
public int Deletions { get; protected set; }
public int Changes { get; protected set; }
public Uri BlobUri { get; protected set; }
public Uri RawUri { get; protected set; }
public Uri ContentsUri { get; protected set; }
public string Patch { get; protected set; }
internal string DebuggerDisplay
{
get { return String.Format(CultureInfo.InvariantCulture, "Sha: {0} Filename: {1} Additions: {2} Deletions: {3} Changes: {4}", Sha, FileName, Additions, Deletions, Changes); }
}
}
}
```
Fix filename not being populated | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Octokit.Internal;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class PullRequestFile
{
public PullRequestFile() { }
public PullRequestFile(string sha, string fileName, string status, int additions, int deletions, int changes, Uri blobUri, Uri rawUri, Uri contentsUri, string patch)
{
Sha = sha;
FileName = fileName;
Status = status;
Additions = additions;
Deletions = deletions;
Changes = changes;
BlobUri = blobUri;
RawUri = rawUri;
ContentsUri = contentsUri;
Patch = patch;
}
public string Sha { get; protected set; }
[Parameter(Key = "filename")]
public string FileName { get; protected set; }
public string Status { get; protected set; }
public int Additions { get; protected set; }
public int Deletions { get; protected set; }
public int Changes { get; protected set; }
public Uri BlobUri { get; protected set; }
public Uri RawUri { get; protected set; }
public Uri ContentsUri { get; protected set; }
public string Patch { get; protected set; }
internal string DebuggerDisplay
{
get { return String.Format(CultureInfo.InvariantCulture, "Sha: {0} FileName: {1} Additions: {2} Deletions: {3} Changes: {4}", Sha, FileName, Additions, Deletions, Changes); }
}
}
}
``` |
7fa08c77-8aa7-49ad-8956-703ddfa6e0d4 | {
"language": "C#"
} | ```c#
@using ParkingSpace.Models
@{
ViewBag.Title = "Index";
var ticket =
(ParkingTicket)TempData["newTicket"];
}
<h2>Gate In [@ViewBag.GateId]</h2>
@using (Html.BeginForm("CreateTicket", "GateIn")) {
<div>
Plate No.:<br />
@Html.TextBox("plateNo")<br />
<br />
<button type="submit" class="btn btn-success">
Issue Parking Ticket
</button>
</div>
}
@if (ticket != null) {
<br/>
<div class="well">
@ticket.Id <br />
@ticket.PlateNumber<br/>
@ticket.DateIn
</div>
}```
Update UI display gate number | ```c#
@using ParkingSpace.Models
@{
ViewBag.Title = "Index";
var ticket =
(ParkingTicket)TempData["newTicket"];
}
<h2>Gate In</h2>
<div class="well well-sm">
<strong>Gate:</strong> @ViewBag.GateId
</div>
@using (Html.BeginForm("CreateTicket", "GateIn")) {
<div>
Plate No.:<br />
@Html.TextBox("plateNo")<br />
<br />
<button type="submit" class="btn btn-success">
Issue Parking Ticket
</button>
</div>
}
@if (ticket != null) {
<br />
<div class="well">
@ticket.Id <br />
@ticket.PlateNumber<br />
@ticket.DateIn
</div>
}``` |
e6cab611-94f7-4e57-9bb1-617bbe7a1be5 | {
"language": "C#"
} | ```c#
using Common.Logging;
using FinnAngelo.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Diagnostics;
namespace FinnAngelo.PomoFishTests
{
[TestClass]
public class IconTests
{
[TestMethod]
//[Ignore]
public void GivenDestroyMethod_WhenGet10000Icons_ThenNoException()
{
//Given
var moqLog = new Mock<ILog>();
var im = new IconManager(moqLog.Object);
//When
for (int a = 0; a < 150; a++)
{
im.SetNotifyIcon(null, Pomodoro.Resting, a);
}
//Then
Assert.IsTrue(true, "this too, shall pass...");
}
}
}
```
Fix a ref to FinnAngelo.PomoFish | ```c#
using Common.Logging;
using FinnAngelo.PomoFish;
using FinnAngelo.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Diagnostics;
namespace FinnAngelo.PomoFishTests
{
[TestClass]
public class IconTests
{
[TestMethod]
//[Ignore]
public void GivenDestroyMethod_WhenGet10000Icons_ThenNoException()
{
//Given
var moqLog = new Mock<ILog>();
var im = new IconManager(moqLog.Object);
//When
for (int a = 0; a < 150; a++)
{
im.SetNotifyIcon(null, Pomodoro.Resting, a);
}
//Then
Assert.IsTrue(true, "this too, shall pass...");
}
}
}
``` |
75231776-1274-4fbf-bc99-4aa0d593fe6f | {
"language": "C#"
} | ```c#
using System;
using EdlinSoftware.Verifier.Tests.Support;
using Xunit;
namespace EdlinSoftware.Verifier.Tests
{
public class CheckTests : IDisposable
{
private readonly StringVerifier _verifier;
private static readonly Action<string> DefaultAssertionFailed = Verifier.AssertionFailed;
public CheckTests()
{
_verifier = new StringVerifier()
.AddVerifiers(sut => VerificationResult.Critical(sut == "success" ? null : "error"));
}
[Fact]
public void Check_Failure_ByDefault()
{
Assert.Throws<VerificationException>(() => _verifier.Check("failure"));
}
[Fact]
public void Check_Success_ByDefault()
{
_verifier.Check("success");
}
[Fact]
public void Check_CustomAssert()
{
Verifier.AssertionFailed = errorMessage => throw new InvalidOperationException(errorMessage);
Assert.Equal(
"error",
Assert.Throws<InvalidOperationException>(() => _verifier.Check("failure")).Message
);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isDisposing)
{
Verifier.AssertionFailed = DefaultAssertionFailed;
}
}
}```
Change Check tests to restore default behaviour | ```c#
using System;
using EdlinSoftware.Verifier.Tests.Support;
using Xunit;
namespace EdlinSoftware.Verifier.Tests
{
public class CheckTests : IDisposable
{
private readonly StringVerifier _verifier;
private static readonly Action<string> DefaultAssertionFailed = Verifier.AssertionFailed;
public CheckTests()
{
Verifier.AssertionFailed = DefaultAssertionFailed;
_verifier = new StringVerifier()
.AddVerifiers(sut => VerificationResult.Critical(sut == "success" ? null : "error"));
}
[Fact]
public void Check_Failure_ByDefault()
{
Assert.Throws<VerificationException>(() => _verifier.Check("failure"));
}
[Fact]
public void Check_Success_ByDefault()
{
_verifier.Check("success");
}
[Fact]
public void Check_CustomAssert()
{
Verifier.AssertionFailed = errorMessage => throw new InvalidOperationException(errorMessage);
Assert.Equal(
"error",
Assert.Throws<InvalidOperationException>(() => _verifier.Check("failure")).Message
);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isDisposing)
{
Verifier.AssertionFailed = DefaultAssertionFailed;
}
}
}``` |
8e1618f8-60c6-43cb-94b8-cb79beb19a39 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Models.PublishedContent;
using Zbu.Blocks.PropertyEditors;
namespace Zbu.Blocks.DataType
{
// note: can cache the converted value at .Content level because it's just
// a deserialized json and it does not reference anything outside its content.
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
[PropertyValueType(typeof(IEnumerable<StructureDataValue>))]
public class StructuresConverter : IPropertyValueConverter
{
public object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
var json = source.ToString();
if (string.IsNullOrWhiteSpace(json)) return null;
var value = JsonSerializer.Instance.Deserialize<StructureDataValue[]>(json);
foreach (var v in value)
v.EnsureFragments(preview);
return value;
}
public object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview)
{
return source;
}
public object ConvertSourceToXPath(PublishedPropertyType propertyType, object source, bool preview)
{
throw new NotImplementedException();
}
public bool IsConverter(PublishedPropertyType propertyType)
{
#if UMBRACO_6
return propertyType.PropertyEditorGuid == StructuresDataType.DataTypeGuid;
#else
return propertyType.PropertyEditorAlias == StructuresPropertyEditor.StructuresAlias;
#endif
}
}
}
```
Implement property converter for XPath | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Models.PublishedContent;
using Zbu.Blocks.PropertyEditors;
namespace Zbu.Blocks.DataType
{
// note: can cache the converted value at .Content level because it's just
// a deserialized json and it does not reference anything outside its content.
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
[PropertyValueType(typeof(IEnumerable<StructureDataValue>))]
public class StructuresConverter : IPropertyValueConverter
{
public object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
// data == source so we can return json to xpath
return source;
}
public object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview)
{
// object == deserialized source
var json = source.ToString();
if (string.IsNullOrWhiteSpace(json)) return null;
var value = JsonSerializer.Instance.Deserialize<StructureDataValue[]>(json);
foreach (var v in value)
v.EnsureFragments(preview);
return value;
}
public object ConvertSourceToXPath(PublishedPropertyType propertyType, object source, bool preview)
{
// we don't really want to support XML for blocks
// so xpath == source == data == the original json
return source;
}
public bool IsConverter(PublishedPropertyType propertyType)
{
#if UMBRACO_6
return propertyType.PropertyEditorGuid == StructuresDataType.DataTypeGuid;
#else
return propertyType.PropertyEditorAlias == StructuresPropertyEditor.StructuresAlias;
#endif
}
}
}
``` |
5e6579b6-9af8-41f2-95af-85909452c7ed | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Parsel
{
internal static class ReplaceParameter
{
public static Expression Apply<S, T>(this Expression<Func<S, T>> f, Expression s)
{
return f.Body.Replace(f.Parameters[0], s);
}
public static Expression Apply<S, T, V>(this Expression<Func<S, T, V>> f, Expression s, Expression t)
{
return f.Body.Replace(f.Parameters[0], s).Replace(f.Parameters[1], s);
}
public static Expression Replace(this Expression body, ParameterExpression parameter, Expression replacement)
{
return new ReplaceParameterVisitor(parameter, replacement).Visit(body);
}
}
internal class ReplaceParameterVisitor : ExpressionVisitor
{
private readonly ParameterExpression parameter;
private readonly Expression replacement;
public ReplaceParameterVisitor(ParameterExpression parameter, Expression replacement)
{
this.parameter = parameter;
this.replacement = replacement;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (node.Equals(parameter))
{
return replacement;
}
else
{
return base.VisitParameter(node);
}
}
}
}
```
Fix error when substituting arguments | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Parsel
{
internal static class ReplaceParameter
{
public static Expression Apply<S, T>(this Expression<Func<S, T>> f, Expression s)
{
return f.Body.Replace(f.Parameters[0], s);
}
public static Expression Apply<S, T, V>(this Expression<Func<S, T, V>> f, Expression s, Expression t)
{
return f.Body.Replace(f.Parameters[0], s).Replace(f.Parameters[1], t);
}
public static Expression Replace(this Expression body, ParameterExpression parameter, Expression replacement)
{
return new ReplaceParameterVisitor(parameter, replacement).Visit(body);
}
}
internal class ReplaceParameterVisitor : ExpressionVisitor
{
private readonly ParameterExpression parameter;
private readonly Expression replacement;
public ReplaceParameterVisitor(ParameterExpression parameter, Expression replacement)
{
this.parameter = parameter;
this.replacement = replacement;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (node.Equals(parameter))
{
return replacement;
}
else
{
return base.VisitParameter(node);
}
}
}
}
``` |
901f3a36-a249-42c5-99e1-9ee929d82e7c | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
using Centroid;
namespace Schedules.API.Tests
{
[TestFixture, Category("System")]
public class SystemTests
{
[Test]
public void CheckThatEnvironmentVariablesExist()
{
dynamic config = Config.FromFile("config.json");
foreach (var variable in config.variables) {
var value = Environment.GetEnvironmentVariable(variable);
Assert.That(!String.IsNullOrEmpty(value), String.Format("{0} does not have a value.", variable));
}
}
}
}
```
Update location of env vars | ```c#
using System;
using NUnit.Framework;
using Centroid;
namespace Schedules.API.Tests
{
[TestFixture, Category("System")]
public class SystemTests
{
[Test]
public void CheckThatEnvironmentVariablesExist()
{
dynamic config = Config.FromFile("config.json");
foreach (var variable in config.all.variables) {
var value = Environment.GetEnvironmentVariable(variable);
Assert.That(!String.IsNullOrEmpty(value), String.Format("{0} does not have a value.", variable));
}
}
}
}
``` |
808f9870-0481-44f5-9ba7-cbc03bb33cde | {
"language": "C#"
} | ```c#
namespace MultiMiner.Win
{
public static class UserAgent
{
public const string AgentString = "MultiMiner/V1";
}
}
```
Update use agent for v2 | ```c#
namespace MultiMiner.Win
{
public static class UserAgent
{
public const string AgentString = "MultiMiner/V2";
}
}
``` |
449bbdf2-a10b-46d8-8a99-db84400a8934 | {
"language": "C#"
} | ```c#
using System.Windows;
using Prism.DryIoc;
using Prism.Ioc;
using SimpSim.NET.WPF.ViewModels;
using SimpSim.NET.WPF.Views;
namespace SimpSim.NET.WPF
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : PrismApplication
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<SimpleSimulator>();
containerRegistry.Register<IUserInputService, UserInputService>();
containerRegistry.Register<IDialogServiceAdapter, DialogServiceAdapter>();
containerRegistry.RegisterSingleton<StateSaver>();
containerRegistry.RegisterDialog<AssemblyEditorDialog, AssemblyEditorDialogViewModel>();
}
}
}
```
Remove unneeded reference to PrismApplication base class. | ```c#
using System.Windows;
using Prism.Ioc;
using SimpSim.NET.WPF.ViewModels;
using SimpSim.NET.WPF.Views;
namespace SimpSim.NET.WPF
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<SimpleSimulator>();
containerRegistry.Register<IUserInputService, UserInputService>();
containerRegistry.Register<IDialogServiceAdapter, DialogServiceAdapter>();
containerRegistry.RegisterSingleton<StateSaver>();
containerRegistry.RegisterDialog<AssemblyEditorDialog, AssemblyEditorDialogViewModel>();
}
}
}
``` |
84a35bd9-d217-417f-87d8-89cc318c0ca7 | {
"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.Threading;
namespace System.Net
{
internal enum SocketPerfCounterName
{
SocketConnectionsEstablished = 0, // these enum values are used as index
SocketBytesReceived,
SocketBytesSent,
SocketDatagramsReceived,
SocketDatagramsSent,
}
internal sealed class SocketPerfCounter
{
private static SocketPerfCounter s_instance;
private static object s_lockObject = new object();
public static SocketPerfCounter Instance
{
get
{
if (Volatile.Read(ref s_instance) == null)
{
lock (s_lockObject)
{
if (Volatile.Read(ref s_instance) == null)
{
s_instance = new SocketPerfCounter();
}
}
}
return s_instance;
}
}
public bool Enabled
{
get
{
// TODO (Event logging for System.Net.* #2500): Implement socket perf counters.
return false;
}
}
public void Increment(SocketPerfCounterName perfCounter)
{
// TODO (Event logging for System.Net.* #2500): Implement socket perf counters.
}
public void Increment(SocketPerfCounterName perfCounter, long amount)
{
// TODO (Event logging for System.Net.* #2500): Implement socket perf counters.
}
}
}
```
Change TODO comments to reference current issue on Sockets perf counters. | ```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.Threading;
namespace System.Net
{
internal enum SocketPerfCounterName
{
SocketConnectionsEstablished = 0, // these enum values are used as index
SocketBytesReceived,
SocketBytesSent,
SocketDatagramsReceived,
SocketDatagramsSent,
}
internal sealed class SocketPerfCounter
{
private static SocketPerfCounter s_instance;
private static object s_lockObject = new object();
public static SocketPerfCounter Instance
{
get
{
if (Volatile.Read(ref s_instance) == null)
{
lock (s_lockObject)
{
if (Volatile.Read(ref s_instance) == null)
{
s_instance = new SocketPerfCounter();
}
}
}
return s_instance;
}
}
public bool Enabled
{
get
{
// TODO (#7833): Implement socket perf counters.
return false;
}
}
public void Increment(SocketPerfCounterName perfCounter)
{
// TODO (#7833): Implement socket perf counters.
}
public void Increment(SocketPerfCounterName perfCounter, long amount)
{
// TODO (#7833): Implement socket perf counters.
}
}
}
``` |
3f8b5d6b-dcb5-4998-bc12-329a337d987e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Oberon0.Compiler.Expressions.Operations
{
using JetBrains.Annotations;
using Oberon0.Compiler.Definitions;
using Oberon0.Compiler.Expressions.Constant;
using Oberon0.Compiler.Expressions.Operations.Internal;
using Oberon0.Compiler.Types;
[ArithmeticOperation(OberonGrammarLexer.OR, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)]
[ArithmeticOperation(OberonGrammarLexer.AND, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)]
[UsedImplicitly]
internal class OpRelOp2 : BinaryOperation
{
protected override Expression BinaryOperate(BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters)
{
if (bin.LeftHandSide.IsConst && bin.RightHandSide.IsConst)
{
var left = (ConstantExpression)bin.LeftHandSide;
var right = (ConstantExpression)bin.RightHandSide;
bool res = false;
switch (operationParameters.Operation)
{
case OberonGrammarLexer.AND:
res = left.ToBool() & right.ToBool();
break;
case OberonGrammarLexer.OR:
res = left.ToBool() || right.ToBool();
break;
}
return new ConstantBoolExpression(res);
}
return bin; // expression remains the same
}
}
}
```
Use && instead of & to perform AND operation | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Oberon0.Compiler.Expressions.Operations
{
using JetBrains.Annotations;
using Oberon0.Compiler.Definitions;
using Oberon0.Compiler.Expressions.Constant;
using Oberon0.Compiler.Expressions.Operations.Internal;
using Oberon0.Compiler.Types;
[ArithmeticOperation(OberonGrammarLexer.OR, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)]
[ArithmeticOperation(OberonGrammarLexer.AND, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)]
[UsedImplicitly]
internal class OpRelOp2 : BinaryOperation
{
protected override Expression BinaryOperate(BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters)
{
if (bin.LeftHandSide.IsConst && bin.RightHandSide.IsConst)
{
var left = (ConstantExpression)bin.LeftHandSide;
var right = (ConstantExpression)bin.RightHandSide;
bool res = false;
switch (operationParameters.Operation)
{
case OberonGrammarLexer.AND:
res = left.ToBool() && right.ToBool();
break;
case OberonGrammarLexer.OR:
res = left.ToBool() || right.ToBool();
break;
}
return new ConstantBoolExpression(res);
}
return bin; // expression remains the same
}
}
}
``` |
ededf9a3-195b-4768-a775-5b0b61362e1e | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Web;
using CommonMark;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers.Web;
namespace JoinRpg.Web.Helpers
{
public static class MarkDownHelper
{
/// <summary>
/// Converts markdown to HtmlString with all sanitization
/// </summary>
[CanBeNull]
public static HtmlString ToHtmlString([CanBeNull] this MarkdownString markdownString)
{
return markdownString?.Contents == null ? null : markdownString.RenderMarkDownToHtmlUnsafe().SanitizeHtml();
}
public static string ToPlainText([CanBeNull] this MarkdownString markdownString)
{
if (markdownString?.Contents == null)
{
return null;
}
return markdownString.RenderMarkDownToHtmlUnsafe().RemoveHtml();
}
private static UnSafeHtml RenderMarkDownToHtmlUnsafe(this MarkdownString markdownString)
{
var settings = CommonMarkSettings.Default.Clone();
settings.RenderSoftLineBreaksAsLineBreaks = true;
return CommonMarkConverter.Convert(markdownString.Contents, settings);
}
public static MarkdownString TakeWords(this MarkdownString markdownString, int words)
{
if (markdownString?.Contents == null)
{
return null;
}
var w = words;
var idx = markdownString.Contents.TakeWhile(c => (w -= char.IsWhiteSpace(c) ? 1 : 0) > 0 && c != '\n').Count();
var mdContents = markdownString.Contents.Substring(0, idx);
return new MarkdownString(mdContents);
}
}
}
```
Fix plots can't edit bug | ```c#
using System.Linq;
using System.Web;
using CommonMark;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers.Web;
namespace JoinRpg.Web.Helpers
{
public static class MarkDownHelper
{
/// <summary>
/// Converts markdown to HtmlString with all sanitization
/// </summary>
[CanBeNull]
public static HtmlString ToHtmlString([CanBeNull] this MarkdownString markdownString)
{
return markdownString?.Contents == null ? null : markdownString.RenderMarkDownToHtmlUnsafe().SanitizeHtml();
}
public static string ToPlainText([CanBeNull] this MarkdownString markdownString)
{
if (markdownString?.Contents == null)
{
return null;
}
return markdownString.RenderMarkDownToHtmlUnsafe().RemoveHtml().Trim();
}
private static UnSafeHtml RenderMarkDownToHtmlUnsafe(this MarkdownString markdownString)
{
var settings = CommonMarkSettings.Default.Clone();
settings.RenderSoftLineBreaksAsLineBreaks = true;
return CommonMarkConverter.Convert(markdownString.Contents, settings);
}
public static MarkdownString TakeWords(this MarkdownString markdownString, int words)
{
if (markdownString?.Contents == null)
{
return null;
}
var w = words;
var idx = markdownString.Contents.TakeWhile(c => (w -= char.IsWhiteSpace(c) ? 1 : 0) > 0 && c != '\n').Count();
var mdContents = markdownString.Contents.Substring(0, idx);
return new MarkdownString(mdContents);
}
}
}
``` |
c8cde734-56ce-44c5-8538-6321ae237d43 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using EloWeb.Models;
using NUnit.Framework;
using System.Collections.Generic;
namespace EloWeb.Tests.UnitTests
{
class PlayersTests
{
[Test]
public void CanParsePlayerDescriptionText()
{
InitialiseTestPlayers();
InitialiseTestGames();
var player = Players.PlayerByName("Richard");
Assert.AreEqual("Richard", player.Name);
Assert.AreEqual(1000, player.Rating);
}
[Test]
public void CanGetPlayerTotalGamesWon()
{
InitialiseTestPlayers();
InitialiseTestGames();
var player = Players.PlayerByName("Frank");
Assert.AreEqual(2, player.GamesWon);
}
[Test]
public void CanGetPlayerTotalGamesLost()
{
InitialiseTestPlayers();
InitialiseTestGames();
var player = Players.PlayerByName("Frank");
Assert.AreEqual(1, player.GamesLost);
}
private void InitialiseTestPlayers()
{
Players.Initialise(new List<String>() { "Peter", "Frank", "Richard" });
}
private void InitialiseTestGames()
{
Games.Initialise(new List<String>() { "Peter beat Frank", "Frank beat Peter", "Frank beat Peter" });
}
}
}
```
Refactor tests to have initialise method | ```c#
using System;
using System.Linq;
using EloWeb.Models;
using NUnit.Framework;
using System.Collections.Generic;
namespace EloWeb.Tests.UnitTests
{
class PlayersTests
{
[TestFixtureSetUp]
public void TestSetup()
{
InitialiseTestPlayers();
InitialiseTestGames();
}
[Test]
public void CanParsePlayerDescriptionText()
{
var player = Players.PlayerByName("Richard");
Assert.AreEqual("Richard", player.Name);
Assert.AreEqual(1000, player.Rating);
}
[Test]
public void CanGetPlayerTotalGamesWon()
{
var player = Players.PlayerByName("Frank");
Assert.AreEqual(2, player.GamesWon);
}
[Test]
public void CanGetPlayerTotalGamesLost()
{
var player = Players.PlayerByName("Frank");
Assert.AreEqual(1, player.GamesLost);
}
private void InitialiseTestPlayers()
{
Players.Initialise(new List<String>() { "Peter", "Frank", "Richard" });
}
private void InitialiseTestGames()
{
Games.Initialise(new List<String>() { "Peter beat Frank", "Frank beat Peter", "Frank beat Peter" });
}
}
}
``` |
446b5492-0632-49df-8e10-543aa3450680 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
namespace NHotkey.Wpf
{
class WeakReferenceCollection<T> : IEnumerable<T>
where T : class
{
private readonly List<WeakReference> _references = new List<WeakReference>();
public IEnumerator<T> GetEnumerator()
{
foreach (var reference in _references)
{
var target = reference.Target;
if (target != null)
yield return (T) target;
}
Trim();
}
public void Add(T item)
{
_references.Add(new WeakReference(item));
}
public void Remove(T item)
{
_references.RemoveAll(r => (r.Target ?? item) == item);
}
public void Trim()
{
_references.RemoveAll(r => !r.IsAlive);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
```
Copy list before iterating to prevent modifications during iteration | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NHotkey.Wpf
{
class WeakReferenceCollection<T> : IEnumerable<T>
where T : class
{
private readonly List<WeakReference> _references = new List<WeakReference>();
public IEnumerator<T> GetEnumerator()
{
var references = _references.ToList();
foreach (var reference in references)
{
var target = reference.Target;
if (target != null)
yield return (T) target;
}
Trim();
}
public void Add(T item)
{
_references.Add(new WeakReference(item));
}
public void Remove(T item)
{
_references.RemoveAll(r => (r.Target ?? item) == item);
}
public void Trim()
{
_references.RemoveAll(r => !r.IsAlive);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
``` |
4c399c86-ea8e-4fee-bbe8-6cc4baa84819 | {
"language": "C#"
} | ```c#
namespace Umbraco.Web.UI
{
/// <summary>
/// This is used for anything that is assigned to an app
/// </summary>
/// <remarks>
/// Currently things that need to be assigned to an app in order for user security to work are:
/// dialogs, ITasks, editors
/// </remarks>
public interface IAssignedApp
{
/// <summary>
/// Returns the app alias that this element belongs to
/// </summary>
string AssignedApp { get; }
}
}
```
Update comment about this Interface usage - maybe we can remove this later on | ```c#
namespace Umbraco.Web.UI
{
/// <summary>
/// This is used for anything that is assigned to an app
/// </summary>
/// <remarks>
/// Currently things that need to be assigned to an app in order for user security to work are:
/// LegacyDialogTask
/// </remarks>
public interface IAssignedApp
{
/// <summary>
/// Returns the app alias that this element belongs to
/// </summary>
string AssignedApp { get; }
}
}
``` |
4637de09-7601-4a30-ad02-28056a203d0e | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Text;
using Xunit.Abstractions;
namespace Foundatio.Tests.Utility {
public class TestOutputWriter : TextWriter {
private readonly ITestOutputHelper _output;
public TestOutputWriter(ITestOutputHelper output) {
_output = output;
}
public override Encoding Encoding {
get { return Encoding.UTF8; }
}
public override void WriteLine(string value) {
_output.WriteLine(value);
}
public override void WriteLine() {
_output.WriteLine(String.Empty);
}
}
}
```
Fix issue where test writer was writing when nothing was listening. | ```c#
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Xunit.Abstractions;
namespace Foundatio.Tests.Utility {
public class TestOutputWriter : TextWriter {
private readonly ITestOutputHelper _output;
public TestOutputWriter(ITestOutputHelper output) {
_output = output;
}
public override Encoding Encoding {
get { return Encoding.UTF8; }
}
public override void WriteLine(string value) {
try {
_output.WriteLine(value);
} catch (Exception ex) {
Trace.WriteLine(ex);
}
}
public override void WriteLine() {
WriteLine(String.Empty);
}
}
}
``` |
1b03c0e1-453c-4079-be80-9c0a2a4074ca | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using Voxelgon.ShipEditor;
namespace Voxelgon.Tests {
public class WallTests {
[Test]
public void WallCannotHaveDuplicateVertices() {
//Arrange
var editor = new ShipEditor.ShipEditor();
var wall = new Wall(editor);
var nodes = new List<Vector3>();
nodes.Add(new Vector3(5, 8, 3));
//Act
wall.UpdateVertices(nodes, ShipEditor.ShipEditor.BuildMode.Polygon);
//Assert
Assert.That(wall.ValidVertex(new Vector3(5, 8, 3)), Is.False);
}
}
}```
Move Shipeditor tests to the Voxelgon.Shipeditor.Tests namespace | ```c#
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using Voxelgon.ShipEditor;
namespace Voxelgon.ShipEditor.Tests {
public class WallTests {
[Test]
public void WallCannotHaveDuplicateVertices() {
//Arrange
var editor = new ShipEditor();
var wall = new Wall(editor);
var nodes = new List<Vector3>();
nodes.Add(new Vector3(5, 8, 3));
//Act
wall.UpdateVertices(nodes, ShipEditor.BuildMode.Polygon);
//Assert
Assert.That(wall.ValidVertex(new Vector3(5, 8, 3)), Is.False);
}
}
}``` |
1dc2f60f-3463-4567-9cb9-36414c781158 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class TwitchRestClientConfig
{
public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/";
}
}
```
Add LogLevel option to restclient config | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class TwitchRestClientConfig
{
public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/";
public LogLevel LogLevel { get; set; } = LogLevel.Errors;
}
}
``` |
01142cc8-c8da-43ce-8bad-7843166b4679 | {
"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.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Setup;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneSetupScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneSetupScreen()
{
editorBeatmap = new EditorBeatmap(new OsuBeatmap());
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Child = new SetupScreen
{
State = { Value = Visibility.Visible },
};
}
}
}
```
Add test coverage for per-ruleset setup screens | ```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.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Catch;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Rulesets.Taiko;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Setup;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneSetupScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneSetupScreen()
{
editorBeatmap = new EditorBeatmap(new OsuBeatmap());
}
[Test]
public void TestOsu() => runForRuleset(new OsuRuleset().RulesetInfo);
[Test]
public void TestTaiko() => runForRuleset(new TaikoRuleset().RulesetInfo);
[Test]
public void TestCatch() => runForRuleset(new CatchRuleset().RulesetInfo);
[Test]
public void TestMania() => runForRuleset(new ManiaRuleset().RulesetInfo);
private void runForRuleset(RulesetInfo rulesetInfo)
{
AddStep("create screen", () =>
{
editorBeatmap.BeatmapInfo.Ruleset = rulesetInfo;
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Child = new SetupScreen
{
State = { Value = Visibility.Visible },
};
});
}
}
}
``` |
3f996009-c9cb-4a21-8b01-9f16d329ad5f | {
"language": "C#"
} | ```c#
namespace TheCollection.Business {
using System.Collections.Generic;
using System.Threading.Tasks;
public interface ISearchRepository<T> where T : class {
Task<IEnumerable<T>> SearchAsync(string searchterm, int top = 0);
}
}
```
Add missing function to interface | ```c#
namespace TheCollection.Business {
using System.Collections.Generic;
using System.Threading.Tasks;
public interface ISearchRepository<T> where T : class {
Task<IEnumerable<T>> SearchAsync(string searchterm, int top = 0);
Task<long> SearchRowCountAsync(string searchterm);
}
}
``` |
fbd4adde-9e8d-41a0-a286-0b98b8308029 | {
"language": "C#"
} | ```c#
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<input type="text" id="msg" />
<a id="broadcast" href="#">Send message</a>
<p>Messages : </p>
<ul id="messages"> </ul>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
$.connection.hub.logging = true;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message, from) {
$('#messages').append('<li>' + message + " from " + from + '</li>');
};
chat.client.onConsoleMessage = function (message) {
$('#messages').append('<li> From the console application : ' + message + '</li>');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val())
.done(function () {
console.log('Success!');
})
.fail(function (e) {
console.warn(e);
});
});
$("#broadcast").hide();
// Start the connection
$.connection.hub.start({transport: 'auto'},function () {
$("#broadcast").show();
console.log("Success");
});
});
</script>
```
Prepend debug messages in the web chat example. | ```c#
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<input type="text" id="msg" />
<a id="broadcast" href="#">Send message</a>
<p>Messages : </p>
<ul id="messages"> </ul>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
$.connection.hub.logging = true;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message, from) {
$('#messages').prepend('<li>' + message + " from " + from + '</li>');
};
chat.client.onConsoleMessage = function (message) {
$('#messages').prepend('<li> From the console application : ' + message + '</li>');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val())
.done(function () {
console.log('Success!');
})
.fail(function (e) {
console.warn(e);
});
});
$("#broadcast").hide();
// Start the connection
$.connection.hub.start({transport: 'auto'},function () {
$("#broadcast").show();
console.log("Success");
});
});
</script>
``` |
06072b54-1b07-4dcb-98ef-9f77d4eb66cc | {
"language": "C#"
} | ```c#
@{
ViewBag.Title = "GAMES";
}
<h2>GAMES:</h2>
<p>list all games here</p>```
Check if appharbour will trigger a build | ```c#
@{
ViewBag.Title = "GAMES";
}
<h2>GAMES:</h2>
<p>list all games here!!!</p>``` |
252c302e-b0f3-46ec-ba52-b8dec7e6ea73 | {
"language": "C#"
} | ```c#
using System;
using FG5eXmlToPDF;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FG5eXmlToPdf.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void ReadWriteTest()
{
var currentDirectory = System.IO.Directory.GetCurrentDirectory();
var character = FG5eXml.LoadCharacter($@"{currentDirectory}\rita.xml");
FG5ePdf.Write(
character,
$@"{currentDirectory}\out.pdf");
}
}
}
```
Test file output using char name and total level. | ```c#
using System;
using System.Linq;
using FG5eXmlToPDF;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FG5eXmlToPdf.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void ReadWriteTest()
{
var currentDirectory = System.IO.Directory.GetCurrentDirectory();
var character = FG5eXml.LoadCharacter($@"{currentDirectory}\rita.xml");
var charName = character.Properities.FirstOrDefault((x) => x.Name == "Name")?.Value;
var level = character.Properities.FirstOrDefault((x) => x.Name == "LevelTotal")?.Value;
FG5ePdf.Write(
character,
$@"{currentDirectory}\{charName} ({level}).pdf");
}
}
}
``` |
6a1d1917-3c46-4a0a-8023-f001f9c4b4e0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TvShowReminderWorker
{
class Program
{
static void Main(string[] args)
{
}
}
}
```
Add text for debug purposes to see if the job has been running | ```c#
using System;
namespace TvShowReminderWorker
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("I am the web job, I ran at {0}", DateTime.Now);
}
}
}
``` |
413cf91f-9d12-442e-9022-61e81d2697e1 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Reflection;
using DanTup.DartAnalysis.Json;
namespace DanTup.DartAnalysis.Tests
{
public abstract class Tests
{
protected string SdkFolder
{
// Hijack ENV-reading property
get { return DanTup.DartVS.DartAnalysisService.SdkPath; }
}
string CodebaseRoot = Path.GetFullPath(new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), @"..\..\..\")).AbsolutePath); // up out of debug, bin, Tests
protected string ServerScript { get { return Path.Combine(CodebaseRoot, "Dart\\AnalysisServer.dart"); } }
protected string SampleDartProject { get { return Path.Combine(CodebaseRoot, "DanTup.DartAnalysis.Tests.SampleDartProject"); } }
protected string HelloWorldFile { get { return SampleDartProject + @"\hello_world.dart"; } }
protected string SingleTypeErrorFile { get { return SampleDartProject + @"\single_type_error.dart"; } }
protected DartAnalysisService CreateTestService()
{
var service = new DartAnalysisService(SdkFolder, ServerScript);
service.SetServerSubscriptions(new[] { ServerService.Status }).Wait();
return service;
}
}
}
```
Add test extension for easier waiting for analysis completion. | ```c#
using System;
using System.IO;
using System.Reactive.Linq;
using System.Reflection;
using DanTup.DartAnalysis.Json;
namespace DanTup.DartAnalysis.Tests
{
public abstract class Tests
{
protected string SdkFolder
{
// Hijack ENV-reading property
get { return DanTup.DartVS.DartAnalysisService.SdkPath; }
}
string CodebaseRoot = Path.GetFullPath(new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), @"..\..\..\")).AbsolutePath); // up out of debug, bin, Tests
protected string ServerScript { get { return Path.Combine(CodebaseRoot, "Dart\\AnalysisServer.dart"); } }
protected string SampleDartProject { get { return Path.Combine(CodebaseRoot, "DanTup.DartAnalysis.Tests.SampleDartProject"); } }
protected string HelloWorldFile { get { return SampleDartProject + @"\hello_world.dart"; } }
protected string SingleTypeErrorFile { get { return SampleDartProject + @"\single_type_error.dart"; } }
protected DartAnalysisService CreateTestService()
{
var service = new DartAnalysisService(SdkFolder, ServerScript);
service.SetServerSubscriptions(new[] { ServerService.Status }).Wait();
return service;
}
}
public static class TestExtensions
{
public static void WaitForAnalysis(this DartAnalysisService service)
{
service
.ServerStatusNotification
.FirstAsync(n => n.Analysis.Analyzing == false)
.Wait();
}
}
}
``` |
93278ab7-c652-4fa2-993f-27a2e29df1cd | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;
namespace NuGet.Dialog.Providers {
internal class PackagesSearchNode : PackagesTreeNodeBase {
private string _searchText;
private readonly PackagesTreeNodeBase _baseNode;
public PackagesTreeNodeBase BaseNode {
get {
return _baseNode;
}
}
public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
base(parent, provider) {
if (baseNode == null) {
throw new ArgumentNullException("baseNode");
}
_searchText = searchText;
_baseNode = baseNode;
// Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
IsSearchResultsNode = true;
}
public override string Name {
get {
return Resources.Dialog_RootNodeSearch;
}
}
public void SetSearchText(string newSearchText) {
if (newSearchText == null) {
throw new ArgumentNullException("newSearchText");
}
if (_searchText != newSearchText) {
_searchText = newSearchText;
if (IsSelected) {
ResetQuery();
Refresh();
}
}
}
public override IQueryable<IPackage> GetPackages() {
return _baseNode.GetPackages().Find(_searchText);
}
}
}```
Reset page number to 1 when perform a new search. Work items: 569 | ```c#
using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;
namespace NuGet.Dialog.Providers {
internal class PackagesSearchNode : PackagesTreeNodeBase {
private string _searchText;
private readonly PackagesTreeNodeBase _baseNode;
public PackagesTreeNodeBase BaseNode {
get {
return _baseNode;
}
}
public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
base(parent, provider) {
if (baseNode == null) {
throw new ArgumentNullException("baseNode");
}
_searchText = searchText;
_baseNode = baseNode;
// Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
IsSearchResultsNode = true;
}
public override string Name {
get {
return Resources.Dialog_RootNodeSearch;
}
}
public void SetSearchText(string newSearchText) {
if (newSearchText == null) {
throw new ArgumentNullException("newSearchText");
}
if (_searchText != newSearchText) {
_searchText = newSearchText;
if (IsSelected) {
ResetQuery();
LoadPage(1);
}
}
}
public override IQueryable<IPackage> GetPackages() {
return _baseNode.GetPackages().Find(_searchText);
}
}
}``` |
449cb663-e7d9-4c84-bb54-4b99c05cb7d7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Establishment {
public class StringEstablisher : BaseClassEstablisher<string> {
public bool IsNullOrEmpty(string value) {
if (!string.IsNullOrEmpty(value)) {
return HandleFailure(new ArgumentException("string value must be null or empty"));
}
return true;
}
public bool IsNotNullOrEmpty(string value) {
if (string.IsNullOrEmpty(value)) {
return HandleFailure(new ArgumentException("string value must not be null or empty"));
}
return true;
}
}
}
```
Add additional comparison methods for string establisher | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Establishment {
public class StringEstablisher : BaseClassEstablisher<string> {
public bool IsNullOrEmpty(string value) {
if (!string.IsNullOrEmpty(value)) {
return HandleFailure(new ArgumentException("string value must be null or empty"));
}
return true;
}
public bool IsNotNullOrEmpty(string value) {
if (string.IsNullOrEmpty(value)) {
return HandleFailure(new ArgumentException("string value must not be null or empty"));
}
return true;
}
public bool IsEmpty(string value) {
if (value != string.Empty) {
return HandleFailure(new ArgumentException("string value must be empty"));
}
return true;
}
public bool IsNotEmpty(string value) {
if (value == string.Empty) {
return HandleFailure(new ArgumentException("string value must not be empty"));
}
return true;
}
}
}
``` |
188ea0f4-20cc-41ce-8f7e-2d785b6534ab | {
"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.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
public class CatchScoreProcessor : ScoreProcessor<CatchHitObject>
{
public CatchScoreProcessor(DrawableRuleset<CatchHitObject> drawableRuleset)
: base(drawableRuleset)
{
}
private float hpDrainRate;
protected override void ApplyBeatmap(Beatmap<CatchHitObject> beatmap)
{
base.ApplyBeatmap(beatmap);
hpDrainRate = beatmap.BeatmapInfo.BaseDifficulty.DrainRate;
}
protected override double HpFactorFor(Judgement judgement, HitResult result)
{
switch (result)
{
case HitResult.Miss when judgement.IsBonus:
return 0;
case HitResult.Miss:
return hpDrainRate;
default:
return 10 - hpDrainRate; // Award less HP as drain rate is increased
}
}
public override HitWindows CreateHitWindows() => new CatchHitWindows();
}
}
```
Make catch provide some HP at DrainRate=10 | ```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.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
public class CatchScoreProcessor : ScoreProcessor<CatchHitObject>
{
public CatchScoreProcessor(DrawableRuleset<CatchHitObject> drawableRuleset)
: base(drawableRuleset)
{
}
private float hpDrainRate;
protected override void ApplyBeatmap(Beatmap<CatchHitObject> beatmap)
{
base.ApplyBeatmap(beatmap);
hpDrainRate = beatmap.BeatmapInfo.BaseDifficulty.DrainRate;
}
protected override double HpFactorFor(Judgement judgement, HitResult result)
{
switch (result)
{
case HitResult.Miss when judgement.IsBonus:
return 0;
case HitResult.Miss:
return hpDrainRate;
default:
return 10.2 - hpDrainRate; // Award less HP as drain rate is increased
}
}
public override HitWindows CreateHitWindows() => new CatchHitWindows();
}
}
``` |
eab4f727-06df-4f28-ab07-dca51ed736f8 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace Gelf.Extensions.Logging
{
public class GelfLoggerOptions
{
public GelfLoggerOptions()
{
Filter = (name, level) => level > LogLevel;
}
/// <summary>
/// GELF server host.
/// </summary>
public string Host { get; set; }
/// <summary>
/// GELF server port.
/// </summary>
public int Port { get; set; } = 12201;
/// <summary>
/// Log source name mapped to the GELF host field.
/// </summary>
public string LogSource { get; set; }
/// <summary>
/// Enable GZip message compression.
/// </summary>
public bool Compress { get; set; } = true;
/// <summary>
/// The message size in bytes under which messages will not be compressed.
/// </summary>
public int CompressionThreshold { get; set; } = 512;
/// <summary>
/// Function used to filter log events based on logger name and level. Uses <see cref="LogLevel"/> by default.
/// </summary>
public Func<string, LogLevel, bool> Filter { get; set; }
/// <summary>
/// The defualt log level.
/// </summary>
public LogLevel LogLevel { get; set; } = LogLevel.Information;
/// <summary>
/// Additional fields that will be attached to all log messages.
/// </summary>
public Dictionary<string, string> AdditionalFields { get; } = new Dictionary<string, string>();
}
}
```
Fix default log level filter | ```c#
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace Gelf.Extensions.Logging
{
public class GelfLoggerOptions
{
public GelfLoggerOptions()
{
Filter = (name, level) => level >= LogLevel;
}
/// <summary>
/// GELF server host.
/// </summary>
public string Host { get; set; }
/// <summary>
/// GELF server port.
/// </summary>
public int Port { get; set; } = 12201;
/// <summary>
/// Log source name mapped to the GELF host field.
/// </summary>
public string LogSource { get; set; }
/// <summary>
/// Enable GZip message compression.
/// </summary>
public bool Compress { get; set; } = true;
/// <summary>
/// The message size in bytes under which messages will not be compressed.
/// </summary>
public int CompressionThreshold { get; set; } = 512;
/// <summary>
/// Function used to filter log events based on logger name and level. Uses <see cref="LogLevel"/> by default.
/// </summary>
public Func<string, LogLevel, bool> Filter { get; set; }
/// <summary>
/// The defualt log level.
/// </summary>
public LogLevel LogLevel { get; set; } = LogLevel.Information;
/// <summary>
/// Additional fields that will be attached to all log messages.
/// </summary>
public Dictionary<string, string> AdditionalFields { get; } = new Dictionary<string, string>();
}
}
``` |
e3911ec3-a688-4339-851c-3d037b6d6d3e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataGenExtensions
{
public static class ObjectExtensions
{
}
}
```
Add object's IsNull & IsNotNull extentions | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataGenExtensions
{
public static class ObjectExtensions
{
public static bool IsNull(this object objectInstance)
{
return objectInstance == null;
}
public static bool IsNotNull(this object objectInstance)
{
return !objectInstance.IsNull();
}
}
}
``` |
e86bc03c-35b4-41fc-8f8a-6b6c806d3a4c | {
"language": "C#"
} | ```c#
using Slicer.Utils.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Slicer.Utils.Validators
{
// Validates data extraction queries
public class DataExtractionQueryValidator
{
Dictionary<string, dynamic> Query;
public DataExtractionQueryValidator(Dictionary<string, dynamic> query)
{
this.Query = query;
}
// Validate data extraction query, if the query is valid will return true
public bool Validator()
{
if (this.Query.ContainsKey("limit"))
{
var limitValue = (int) this.Query["limit"];
if (limitValue > 100)
{
throw new InvalidQueryException("The field 'limit' has a value max of 100.");
}
}
if (this.Query.ContainsKey("fields"))
{
var fields = this.Query["fields"];
if (fields.Count > 10)
{
throw new InvalidQueryException("The key 'fields' in data extraction result must have up to 10 fields.");
}
}
return true;
}
}
}
```
Remove limit check on data extraction queries | ```c#
using Slicer.Utils.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Slicer.Utils.Validators
{
// Validates data extraction queries
public class DataExtractionQueryValidator
{
Dictionary<string, dynamic> Query;
public DataExtractionQueryValidator(Dictionary<string, dynamic> query)
{
this.Query = query;
}
// Validate data extraction query, if the query is valid will return true
public bool Validator()
{
if (this.Query.ContainsKey("fields"))
{
var fields = this.Query["fields"];
if (fields.Count > 10)
{
throw new InvalidQueryException("The key 'fields' in data extraction result must have up to 10 fields.");
}
}
return true;
}
}
}
``` |
451d14d4-df53-4a72-b74c-4399e93775da | {
"language": "C#"
} | ```c#
namespace Tabster.Core.Plugins
{
public interface ITabsterPlugin
{
string Name { get; }
string Description { get; }
string Author { get; }
string Version { get; }
string[] PluginClasses { get; }
}
}
```
Use types instead of fully qualified names. | ```c#
using System;
namespace Tabster.Core.Plugins
{
public interface ITabsterPlugin
{
string Name { get; }
string Description { get; }
string Author { get; }
string Version { get; }
Type[] Types { get; }
}
}
``` |
f43174bb-256e-42d8-806f-198fad38755b | {
"language": "C#"
} | ```c#
using UnityEngine;
public class Application : MonoBehaviour
{
public ModelContainer Model;
public ControllerContainer Controller;
public ViewContainer View;
}```
Add possibility to register events on App, like we do on HTML DOM | ```c#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Application : MonoBehaviour
{
public ModelContainer Model;
public ControllerContainer Controller;
public ViewContainer View;
private Dictionary<string, UnityEvent> eventDictionary = new Dictionary<string, UnityEvent>();
/// <summary>
/// Add listener to a given event.
/// </summary>
/// <param name="eventName">Name of the event.</param>
/// <param name="listener">Callback function.</param>
public void AddEventListener(string eventName, UnityAction listener)
{
UnityEvent e;
if (eventDictionary.TryGetValue(eventName, out e))
{
e.AddListener(listener);
}
else
{
e = new UnityEvent();
e.AddListener(listener);
eventDictionary.Add(eventName, e);
}
}
/// <summary>
/// Remove listener from a given event.
/// </summary>
/// <param name="eventName">Name of the event.</param>
/// <param name="listener">Callback function.</param>
public void RemoveEventListener(string eventName, UnityAction listener)
{
UnityEvent e;
if (eventDictionary.TryGetValue(eventName, out e))
{
e.RemoveListener(listener);
}
}
/// <summary>
/// Triggers all registered callbacks of a given event.
/// </summary>
public void TriggerEvent(string eventName)
{
UnityEvent e;
if (eventDictionary.TryGetValue(eventName, out e))
{
e.Invoke();
}
}
}``` |
1ef8e0fb-2562-40f5-a047-03d9057ac694 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using LiteNetLib;
namespace LiteNetLibHighLevel
{
public class LiteNetLibPlayer
{
public LiteNetLibGameManager Manager { get; protected set; }
public NetPeer Peer { get; protected set; }
public long ConnectId { get { return Peer.ConnectId; } }
public readonly Dictionary<uint, LiteNetLibIdentity> SpawnedObjects = new Dictionary<uint, LiteNetLibIdentity>();
public LiteNetLibPlayer(LiteNetLibGameManager manager, NetPeer peer)
{
Manager = manager;
Peer = peer;
}
internal void DestoryAllObjects()
{
foreach (var spawnedObject in SpawnedObjects)
Manager.Assets.NetworkDestroy(spawnedObject.Key);
}
}
}
```
Fix out of sync bugs | ```c#
using System.Collections;
using System.Collections.Generic;
using LiteNetLib;
namespace LiteNetLibHighLevel
{
public class LiteNetLibPlayer
{
public LiteNetLibGameManager Manager { get; protected set; }
public NetPeer Peer { get; protected set; }
public long ConnectId { get { return Peer.ConnectId; } }
internal readonly Dictionary<uint, LiteNetLibIdentity> SpawnedObjects = new Dictionary<uint, LiteNetLibIdentity>();
public LiteNetLibPlayer(LiteNetLibGameManager manager, NetPeer peer)
{
Manager = manager;
Peer = peer;
}
internal void DestoryAllObjects()
{
var objectIds = new List<uint>(SpawnedObjects.Keys);
foreach (var objectId in objectIds)
Manager.Assets.NetworkDestroy(objectId);
}
}
}
``` |
b8cc002d-c244-4d89-a82b-9913d18f6d05 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZocBuild.Database.Errors
{
public class MismatchedSchemaError : BuildErrorBase
{
public MismatchedSchemaError(string objectName, string expected, string actual)
{
ActualSchemaName = actual;
ExpectedSchemaName = expected;
ObjectName = objectName;
}
public string ActualSchemaName { get; private set; }
public string ExpectedSchemaName { get; private set; }
public string ObjectName { get; private set; }
public override string ErrorType
{
get { return "Mismatched Schema"; }
}
public override string GetMessage()
{
return string.Format("Cannot use script of schema {2} for {1} when expecting schema {0}.", ObjectName, ExpectedSchemaName, ActualSchemaName);
}
public override BuildItem.BuildStatusType Status
{
get { return BuildItem.BuildStatusType.ScriptError; }
}
}
}
```
Fix string format in error message | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZocBuild.Database.Errors
{
public class MismatchedSchemaError : BuildErrorBase
{
public MismatchedSchemaError(string objectName, string expected, string actual)
{
ActualSchemaName = actual;
ExpectedSchemaName = expected;
ObjectName = objectName;
}
public string ActualSchemaName { get; private set; }
public string ExpectedSchemaName { get; private set; }
public string ObjectName { get; private set; }
public override string ErrorType
{
get { return "Mismatched Schema"; }
}
public override string GetMessage()
{
return string.Format("Cannot use script of schema {2} for {0} when expecting schema {1}.", ObjectName, ExpectedSchemaName, ActualSchemaName);
}
public override BuildItem.BuildStatusType Status
{
get { return BuildItem.BuildStatusType.ScriptError; }
}
}
}
``` |
2c359968-54f1-4710-bff2-abdb4dc28996 | {
"language": "C#"
} | ```c#
using System.Web;
using Microsoft.Web.Infrastructure;
namespace BoC.Web
{
public class ApplicationStarterHttpModule : IHttpModule
{
private static object lockObject = new object();
private static bool startWasCalled = false;
public static void StartApplication()
{
if (startWasCalled || Initializer.Executed)
return;
try
{
lock (lockObject)
{
if (startWasCalled)
return;
Initializer.Execute();
startWasCalled = true;
}
}
catch
{
InfrastructureHelper.UnloadAppDomain();
throw;
}
}
public void Init(HttpApplication context)
{
context.BeginRequest += (sender, args) => StartApplication();
if (!startWasCalled)
{
try
{
context.Application.Lock();
StartApplication();
}
finally
{
context.Application.UnLock();
}
}
}
public void Dispose()
{
}
}
}
```
Allow to disable the application-starter | ```c#
using System;
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using Microsoft.Web.Infrastructure;
namespace BoC.Web
{
public class ApplicationStarterHttpModule : IHttpModule
{
private static object lockObject = new object();
private static bool startWasCalled = false;
public static volatile bool Disabled = false;
public static void StartApplication()
{
if (Disabled || startWasCalled || Initializer.Executed)
return;
try
{
lock (lockObject)
{
var disabled = WebConfigurationManager.AppSettings["BoC.Web.DisableAutoStart"];
if ("true".Equals(disabled, StringComparison.InvariantCultureIgnoreCase))
{
Disabled = true;
return;
}
if (startWasCalled)
return;
Initializer.Execute();
startWasCalled = true;
}
}
catch
{
InfrastructureHelper.UnloadAppDomain();
throw;
}
}
public void Init(HttpApplication context)
{
if (Disabled)
return;
context.BeginRequest += (sender, args) => StartApplication();
if (!Disabled && !startWasCalled)
{
try
{
context.Application.Lock();
StartApplication();
}
finally
{
context.Application.UnLock();
}
}
}
public void Dispose()
{
}
}
}
``` |
1fc3886e-725c-4ffa-80d5-910bfd4276f4 | {
"language": "C#"
} | ```c#
using Android.App;
using Android.Widget;
using Android.OS;
namespace TwitterMonkey
{
[Activity (Label = "TwitterMonkey", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
button.Text = string.Format ("{0} clicks!", count++);
};
}
}
}
```
Add simple mechanism to fetch JSON and display it | ```c#
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Android.App;
using Android.OS;
using Android.Widget;
using TwitterMonkey.Portable;
namespace TwitterMonkey {
[Activity(Label = "TwitterMonkey", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity {
protected override void OnCreate (Bundle bundle) {
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += async (sender, e) => {
var textView = FindViewById<TextView>(Resource.Id.textView1);
var jsonString = await fetchJsonAsync(new Uri ("http://goo.gl/pJwOUS"));
var tweets = TweetConverter.ConvertAll(jsonString);
foreach (Tweet t in tweets) {
textView.Text += t.Message + "\n";
}
};
}
private async Task<string> fetchJsonAsync (Uri uri) {
HttpWebRequest request = new HttpWebRequest(uri);
var resp = await request.GetResponseAsync();
StreamReader reader = new StreamReader (resp.GetResponseStream());
return await reader.ReadToEndAsync();
}
}
}
``` |
d46e5636-f26a-4a60-8795-e539c2a1d543 | {
"language": "C#"
} | ```c#
using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;
namespace BluetoothLE.Example.Droid
{
[Activity(Label = "BluetoothLE.Example.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
DependencyService.Register<IAdapter, Adapter>();
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
```
Update IAdapter registration in Droid example project | ```c#
using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;
namespace BluetoothLE.Example.Droid
{
[Activity(Label = "BluetoothLE.Example.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
DependencyService.Register<BluetoothLE.Core.IAdapter, BluetoothLE.Droid.Adapter>();
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
``` |
d28c29fb-70e5-46bb-a805-ac73be00bd70 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Rulesets.Osu.Objects
{
public class RepeatPoint : OsuHitObject
{
public int RepeatIndex { get; set; }
public double SpanDuration { get; set; }
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
// We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders
// we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time.
if (RepeatIndex > 0)
TimePreempt = Math.Min(SpanDuration * 2, TimePreempt);
}
}
}
```
Fix slider repeat points appearing far too late | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Rulesets.Osu.Objects
{
public class RepeatPoint : OsuHitObject
{
public int RepeatIndex { get; set; }
public double SpanDuration { get; set; }
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
// Out preempt should be one span early to give the user ample warning.
TimePreempt += SpanDuration;
// We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders
// we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time.
if (RepeatIndex > 0)
TimePreempt = Math.Min(SpanDuration * 2, TimePreempt);
}
}
}
``` |
d2b90c74-049c-4f59-ad02-59c63870aae5 | {
"language": "C#"
} | ```c#
//
// ReadRegisters.cs
//
// Author:
// Benito Palacios Sánchez <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
namespace NitroDebugger.RSP.Packets
{
public class ReadRegisters : CommandPacket
{
public ReadRegisters()
: base('g')
{
}
protected override string PackArguments()
{
return "";
}
}
}
```
Fix typo that don't compile. | ```c#
//
// ReadRegisters.cs
//
// Author:
// Benito Palacios Sánchez <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
namespace NitroDebugger.RSP.Packets
{
public class ReadRegisters : CommandPacket
{
public ReadRegisters()
: base("g")
{
}
protected override string PackArguments()
{
return "";
}
}
}
``` |
236fbce0-1a58-4aa4-85a5-589795406854 | {
"language": "C#"
} | ```c#
namespace Octokit
{
public interface IActivitiesClient
{
IEventsClient Event { get; }
}
}```
Apply naming suppression to allow build to build. | ```c#
namespace Octokit
{
public interface IActivitiesClient
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Event")]
IEventsClient Event { get; }
}
}``` |
2dd2b1b4-5cd1-4c50-9351-950848ed4496 | {
"language": "C#"
} | ```c#
namespace Espera.Network
{
public enum PushAction
{
UpdateAccessPermission = 0,
UpdateCurrentPlaylist = 1,
UpdatePlaybackState = 2,
UpdateRemainingVotes = 3
}
}```
Add a playback time push message | ```c#
namespace Espera.Network
{
public enum PushAction
{
UpdateAccessPermission = 0,
UpdateCurrentPlaylist = 1,
UpdatePlaybackState = 2,
UpdateRemainingVotes = 3,
UpdateCurrentPlaybackTime = 4
}
}``` |
a935e860-a660-462f-adbc-89280172235d | {
"language": "C#"
} | ```c#
using System;
namespace Mios.Localization.Localizers {
public class NullLocalizer {
public static LocalizedString Instance(string key, params object[] args) {
return new LocalizedString(String.Format(key,args), null);
}
}
}
```
Fix exception when dumping a null parameter | ```c#
using System;
using System.Linq;
namespace Mios.Localization.Localizers {
public class NullLocalizer {
public static LocalizedString Instance(string key, params object[] args) {
var parameters = args.Any()
? "["+String.Join(",",args.Select(t=>(t??String.Empty).ToString()).ToArray())+"]"
: String.Empty;
return new LocalizedString(key+parameters, null);
}
}
}
``` |
6eed33b0-de5f-4e38-a270-83c697c9df9f | {
"language": "C#"
} | ```c#
namespace Nancy.Linker.Tests
{
using System.Runtime.InteropServices;
using Testing;
using Xunit;
public class ResourceLinkerTests
{
private Browser app;
public class TestModule : NancyModule
{
public static ResourceLinker linker;
public TestModule(ResourceLinker linker)
{
TestModule.linker = linker;
Get["foo", "/foo"] = _ => 200;
Get["bar", "/bar/{id}"] = _ => 200;
}
}
public ResourceLinkerTests()
{
app = new Browser(with => with.Module<TestModule>(), defaults: to => to.HostName("localhost"));
}
[Fact]
public void Link_generated_is_correct_when_base_uri_has_trailing_slash()
{
var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "foo", new {});
Assert.Equal("http://localhost/foo", uriString.ToString());
}
[Fact]
public void Link_generated_is_correct_with_bound_parameter()
{
var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new {id = 123 });
Assert.Equal("http://localhost/bar/123", uriString.ToString());
}
[Fact]
public void Argument_exception_is_thrown_if_parameter_from_template_cannot_be_bound()
{
}
}
}```
Change naming in test and add one | ```c#
namespace Nancy.Linker.Tests
{
using System;
using System.Runtime.InteropServices;
using Testing;
using Xunit;
public class ResourceLinker_Should
{
private Browser app;
public class TestModule : NancyModule
{
public static ResourceLinker linker;
public TestModule(ResourceLinker linker)
{
TestModule.linker = linker;
Get["foo", "/foo"] = _ => 200;
Get["bar", "/bar/{id}"] = _ => 200;
}
}
public ResourceLinker_Should()
{
app = new Browser(with => with.Module<TestModule>(), defaults: to => to.HostName("localhost"));
}
[Fact]
public void generate_absolute_uri_correctly_when_route_has_no_params()
{
var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "foo", new {});
Assert.Equal("http://localhost/foo", uriString.ToString());
}
[Fact]
public void generate_absolute_uri_correctly_when_route_has_params()
{
var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new {id = 123 });
Assert.Equal("http://localhost/bar/123", uriString.ToString());
}
[Fact]
public void throw_if_parameter_from_template_cannot_be_bound()
{
Assert.Throws<ArgumentException>(() =>
TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new { })
);
}
}
}``` |
70b1ee6d-fc1c-4886-a672-505a6b532203 | {
"language": "C#"
} | ```c#
using NBi.Core.Transformation.Transformer.Native;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Transformation.Transformer
{
public class NativeTransformationFactory
{
public INativeTransformation Instantiate(string code)
{
var textInfo = CultureInfo.InvariantCulture.TextInfo;
var parameters = code.Replace("(", ",")
.Replace(")", ",")
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.ToList().Skip(1).Select(x => x.Trim()).ToArray();
var classToken = code.Contains("(") ? code.Replace(" ", "").Substring(0, code.IndexOf('(')) : code;
var className = textInfo.ToTitleCase(classToken.Trim().Replace("-", " ")).Replace(" ", "").Replace("Datetime", "DateTime");
var clazz = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(t => t.GetTypes())
.Where(
t => t.IsClass
&& t.IsAbstract == false
&& t.Name == className
&& t.GetInterface("INativeTransformation") != null)
.SingleOrDefault();
if (clazz == null)
throw new NotImplementedTransformationException(className);
return (INativeTransformation)Activator.CreateInstance(clazz, parameters);
}
}
}
```
Fix bugs that native functions with parameters are not instantiable due to parsing mistakes | ```c#
using NBi.Core.Transformation.Transformer.Native;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Transformation.Transformer
{
public class NativeTransformationFactory
{
public INativeTransformation Instantiate(string code)
{
var textInfo = CultureInfo.InvariantCulture.TextInfo;
var parameters = code.Replace("(", ",")
.Replace(")", ",")
.Replace(" ", "")
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.ToList().Skip(1).Select(x => x.Trim()).ToArray();
var classToken = code.Contains("(") ? code.Replace(" ", "").Substring(0, code.IndexOf('(') - 1) : code;
var className = textInfo.ToTitleCase(classToken.Trim().Replace("-", " ")).Replace(" ", "").Replace("Datetime", "DateTime");
var clazz = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(t => t.GetTypes())
.Where(
t => t.IsClass
&& t.IsAbstract == false
&& t.Name == className
&& t.GetInterface("INativeTransformation") != null)
.SingleOrDefault();
if (clazz == null)
throw new NotImplementedTransformationException(className);
return (INativeTransformation)Activator.CreateInstance(clazz, parameters);
}
}
}
``` |
f42df198-9aff-4c2f-9071-2a541093e12a | {
"language": "C#"
} | ```c#
using umbraco;
using Umbraco.Core.IO;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Trees
{
/// <summary>
/// Tree for displaying partial views in the settings app
/// </summary>
[Tree(Constants.Applications.Settings, Constants.Trees.PartialViews, null, sortOrder: 7)]
[UmbracoTreeAuthorize(Constants.Trees.PartialViews)]
[PluginController("UmbracoTrees")]
[CoreTree(TreeGroup = Constants.Trees.Groups.Templating)]
public class PartialViewsTreeController : FileSystemTreeController
{
protected override IFileSystem FileSystem => Current.FileSystems.PartialViewsFileSystem;
private static readonly string[] ExtensionsStatic = {"cshtml"};
protected override string[] Extensions => ExtensionsStatic;
protected override string FileIcon => "icon-article";
protected override void OnRenderFolderNode(ref TreeNode treeNode)
{
//TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now.
treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);";
treeNode.Icon = "icon-article";
}
}
}
```
Fix PartialView Tree Controller to display a folder icon as opposed to an article icon for nested folders - looks odd/broken to me otherwise | ```c#
using umbraco;
using Umbraco.Core.IO;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Trees
{
/// <summary>
/// Tree for displaying partial views in the settings app
/// </summary>
[Tree(Constants.Applications.Settings, Constants.Trees.PartialViews, null, sortOrder: 7)]
[UmbracoTreeAuthorize(Constants.Trees.PartialViews)]
[PluginController("UmbracoTrees")]
[CoreTree(TreeGroup = Constants.Trees.Groups.Templating)]
public class PartialViewsTreeController : FileSystemTreeController
{
protected override IFileSystem FileSystem => Current.FileSystems.PartialViewsFileSystem;
private static readonly string[] ExtensionsStatic = {"cshtml"};
protected override string[] Extensions => ExtensionsStatic;
protected override string FileIcon => "icon-article";
protected override void OnRenderFolderNode(ref TreeNode treeNode)
{
//TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now.
treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);";
treeNode.Icon = "icon-folder";
}
}
}
``` |
3cd31046-6bbd-4ccd-9bf5-85b62ce23b9e | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Elders.Cronus.Discoveries;
using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;
namespace Elders.Cronus.Transport.RabbitMQ
{
public class RabbitMqPublisherDiscovery : DiscoveryBasedOnExecutingDirAssemblies<IPublisher<IMessage>>
{
protected override DiscoveryResult<IPublisher<IMessage>> DiscoverFromAssemblies(DiscoveryContext context)
{
return new DiscoveryResult<IPublisher<IMessage>>(GetModels());
}
IEnumerable<DiscoveredModel> GetModels()
{
yield return new DiscoveredModel(typeof(RabbitMqSettings), typeof(RabbitMqSettings), ServiceLifetime.Singleton);
yield return new DiscoveredModel(typeof(IConnectionFactory), typeof(RabbitMqConnectionFactory), ServiceLifetime.Singleton);
yield return new DiscoveredModel(typeof(IPublisher<>), typeof(RabbitMqPublisher<>), ServiceLifetime.Singleton);
}
}
}
```
Mark IPublisher<> descriptor as overrider | ```c#
using System.Collections.Generic;
using Elders.Cronus.Discoveries;
using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;
namespace Elders.Cronus.Transport.RabbitMQ
{
public class RabbitMqPublisherDiscovery : DiscoveryBasedOnExecutingDirAssemblies<IPublisher<IMessage>>
{
protected override DiscoveryResult<IPublisher<IMessage>> DiscoverFromAssemblies(DiscoveryContext context)
{
return new DiscoveryResult<IPublisher<IMessage>>(GetModels());
}
IEnumerable<DiscoveredModel> GetModels()
{
yield return new DiscoveredModel(typeof(RabbitMqSettings), typeof(RabbitMqSettings), ServiceLifetime.Singleton);
yield return new DiscoveredModel(typeof(IConnectionFactory), typeof(RabbitMqConnectionFactory), ServiceLifetime.Singleton);
var publisherModel = new DiscoveredModel(typeof(IPublisher<>), typeof(RabbitMqPublisher<>), ServiceLifetime.Singleton);
publisherModel.CanOverrideDefaults = true;
yield return publisherModel;
}
}
}
``` |
85f411be-08ae-4271-83c9-083a153296bf | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
namespace TicketTimer.Core.Infrastructure
{
public class JsonWorkItemStore : WorkItemStore
{
private readonly FileStore _fileStore;
private const string FileName = "timer.state";
private TimerState _state;
public JsonWorkItemStore(FileStore fileStore)
{
_fileStore = fileStore;
Load();
}
public void AddToArchive(WorkItem workItem)
{
GetState().WorkItemArchive.Add(workItem);
Save();
}
public TimerState GetState()
{
if (_state == null)
{
Load();
}
return _state;
}
public void Save()
{
var json = JsonConvert.SerializeObject(_state);
_fileStore.WriteFile(json, FileName);
}
private void Load()
{
var json = _fileStore.ReadFile(FileName);
if (!string.IsNullOrEmpty(json))
{
_state = JsonConvert.DeserializeObject<TimerState>(json);
}
else
{
_state = new TimerState();
}
}
public void SetCurrent(WorkItem workItem)
{
GetState().CurrentWorkItem = workItem;
Save();
}
public void ClearArchive()
{
GetState().WorkItemArchive.Clear();
Save();
}
}
}
```
Write JSON as prettified string to file for better readability. | ```c#
using Newtonsoft.Json;
namespace TicketTimer.Core.Infrastructure
{
public class JsonWorkItemStore : WorkItemStore
{
private readonly FileStore _fileStore;
private const string FileName = "timer.state";
private TimerState _state;
public JsonWorkItemStore(FileStore fileStore)
{
_fileStore = fileStore;
Load();
}
public void AddToArchive(WorkItem workItem)
{
GetState().WorkItemArchive.Add(workItem);
Save();
}
public TimerState GetState()
{
if (_state == null)
{
Load();
}
return _state;
}
public void Save()
{
var json = JsonConvert.SerializeObject(_state, Formatting.Indented);
_fileStore.WriteFile(json, FileName);
}
private void Load()
{
var json = _fileStore.ReadFile(FileName);
if (!string.IsNullOrEmpty(json))
{
_state = JsonConvert.DeserializeObject<TimerState>(json);
}
else
{
_state = new TimerState();
}
}
public void SetCurrent(WorkItem workItem)
{
GetState().CurrentWorkItem = workItem;
Save();
}
public void ClearArchive()
{
GetState().WorkItemArchive.Clear();
Save();
}
}
}
``` |
9438b7bd-bfc9-4062-a251-47d44322a4fc | {
"language": "C#"
} | ```c#
using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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: AssemblyInformationalVersion("1.0.0-alpha01")]```
Increase assembly version to 'beta01' | ```c#
using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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: AssemblyInformationalVersion("1.0.0-beta01")]``` |
9c32b9a4-415b-4431-972b-c7ebc6fddff8 | {
"language": "C#"
} | ```c#
using Rainbow.Model;
namespace Rainbow.Diff.Fields
{
public class DefaultComparison : IFieldComparer
{
public bool CanCompare(IItemFieldValue field1, IItemFieldValue field2)
{
return field1 != null && field2 != null;
}
public bool AreEqual(IItemFieldValue field1, IItemFieldValue field2)
{
if (field1.Value == null || field2.Value == null) return false;
if (field1.BlobId.HasValue && field2.BlobId.HasValue) return field1.BlobId.Value.Equals(field2.BlobId.Value);
return field1.Value.Equals(field2.Value);
}
}
}
```
Improve comparison order to avoid reading blob values by mistake | ```c#
using Rainbow.Model;
namespace Rainbow.Diff.Fields
{
public class DefaultComparison : IFieldComparer
{
public bool CanCompare(IItemFieldValue field1, IItemFieldValue field2)
{
return field1 != null && field2 != null;
}
public bool AreEqual(IItemFieldValue field1, IItemFieldValue field2)
{
if (field1.BlobId.HasValue && field2.BlobId.HasValue) return field1.BlobId.Value.Equals(field2.BlobId.Value);
var field1Value = field1.Value;
var field2Value = field2.Value;
if (field1Value == null || field2Value == null) return false;
return field1Value.Equals(field2Value);
}
}
}
``` |
b5d0de92-3227-44dc-9ccd-891eb0a598f2 | {
"language": "C#"
} | ```c#
namespace Simple.Web.Behaviors.Implementations
{
using MediaTypeHandling;
using Behaviors;
using Http;
/// <summary>
/// This type supports the framework directly and should not be used from your code.
/// </summary>
public static class SetInput
{
/// <summary>
/// This method supports the framework directly and should not be used from your code
/// </summary>
/// <typeparam name="T">The input model type.</typeparam>
/// <param name="handler">The handler.</param>
/// <param name="context">The context.</param>
public static void Impl<T>(IInput<T> handler, IContext context)
{
if (context.Request.InputStream.Length == 0) return;
var mediaTypeHandlerTable = new MediaTypeHandlerTable();
var mediaTypeHandler = mediaTypeHandlerTable.GetMediaTypeHandler(context.Request.GetContentType());
handler.Input = (T)mediaTypeHandler.Read(context.Request.InputStream, typeof(T));
}
}
}
```
Check InputStream on when seekable. | ```c#
namespace Simple.Web.Behaviors.Implementations
{
using MediaTypeHandling;
using Behaviors;
using Http;
/// <summary>
/// This type supports the framework directly and should not be used from your code.
/// </summary>
public static class SetInput
{
/// <summary>
/// This method supports the framework directly and should not be used from your code
/// </summary>
/// <typeparam name="T">The input model type.</typeparam>
/// <param name="handler">The handler.</param>
/// <param name="context">The context.</param>
public static void Impl<T>(IInput<T> handler, IContext context)
{
if (context.Request.InputStream.CanSeek && context.Request.InputStream.Length == 0)
{
return;
}
var mediaTypeHandlerTable = new MediaTypeHandlerTable();
var mediaTypeHandler = mediaTypeHandlerTable.GetMediaTypeHandler(context.Request.GetContentType());
handler.Input = (T)mediaTypeHandler.Read(context.Request.InputStream, typeof(T));
}
}
}
``` |
077ab57a-b3e8-42ff-883a-3439e122af3b | {
"language": "C#"
} | ```c#
namespace Application.Business.Models
{
using System.ComponentModel.DataAnnotations;
public class ResetPasswordFromMailModel
{
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Token")]
public string Token { get; set; }
}
}
```
Fix bug with require token field in register page | ```c#
namespace Application.Business.Models
{
using System.ComponentModel.DataAnnotations;
public class ResetPasswordFromMailModel
{
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Token")]
public string Token { get; set; }
}
}
``` |
d6eb7940-9c36-48e5-a2e4-d9f33d1fe77a | {
"language": "C#"
} | ```c#
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2016
{
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Day16"/> class. This class cannot be inherited.
/// </summary>
public static class Day16Tests
{
[Theory]
[InlineData("110010110100", 12, "100")]
[InlineData("10000", 20, "01100")]
public static void Y2016_Day16_GetDiskChecksum_Returns_Correct_Solution(string initial, int size, string expected)
{
// Act
string actual = Day16.GetDiskChecksum(initial, size);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public static void Y2016_Day16_Solve_Returns_Correct_Solution()
{
// Arrange
string[] args = new[] { "10010000000110000", "272" };
// Act
var puzzle = PuzzleTestHelpers.SolvePuzzle<Day16>(args);
// Assert
Assert.Equal("10010110010011110", puzzle.Checksum);
}
}
}
```
Solve day 16 part 2 | ```c#
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2016
{
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Day16"/> class. This class cannot be inherited.
/// </summary>
public static class Day16Tests
{
[Theory]
[InlineData("110010110100", 12, "100")]
[InlineData("10000", 20, "01100")]
public static void Y2016_Day16_GetDiskChecksum_Returns_Correct_Solution(string initial, int size, string expected)
{
// Act
string actual = Day16.GetDiskChecksum(initial, size);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("272", "10010110010011110")]
[InlineData("35651584", "01101011101100011")]
public static void Y2016_Day16_Solve_Returns_Correct_Solution(string size, string expected)
{
// Arrange
string[] args = new[] { "10010000000110000", size };
// Act
var puzzle = PuzzleTestHelpers.SolvePuzzle<Day16>(args);
// Assert
Assert.Equal(expected, puzzle.Checksum);
}
}
}
``` |
f19a1e43-5ae4-44a2-a3ca-8e5820292c50 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Overlays.Chat.ChannelList
{
public class ChannelListItemCloseButton : OsuAnimatedButton
{
[BackgroundDependencyLoader]
private void load(OsuColour osuColour)
{
Alpha = 0f;
Size = new Vector2(20);
Add(new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(0.75f),
Icon = FontAwesome.Solid.TimesCircle,
RelativeSizeAxes = Axes.Both,
Colour = osuColour.Red1,
});
}
}
}
```
Remove box surrounding close button | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Chat.ChannelList
{
public class ChannelListItemCloseButton : OsuClickableContainer
{
private SpriteIcon icon = null!;
private Color4 normalColour;
private Color4 hoveredColour;
[BackgroundDependencyLoader]
private void load(OsuColour osuColour)
{
normalColour = osuColour.Red2;
hoveredColour = Color4.White;
Alpha = 0f;
Size = new Vector2(20);
Add(icon = new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(0.75f),
Icon = FontAwesome.Solid.TimesCircle,
RelativeSizeAxes = Axes.Both,
Colour = normalColour,
});
}
// Transforms matching OsuAnimatedButton
protected override bool OnHover(HoverEvent e)
{
icon.FadeColour(hoveredColour, 300, Easing.OutQuint);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
icon.FadeColour(normalColour, 300, Easing.OutQuint);
base.OnHoverLost(e);
}
protected override bool OnMouseDown(MouseDownEvent e)
{
icon.ScaleTo(0.75f, 2000, Easing.OutQuint);
return base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseUpEvent e)
{
icon.ScaleTo(1, 1000, Easing.OutElastic);
base.OnMouseUp(e);
}
}
}
``` |
b760c214-f7a8-4c34-8f2e-1f6fca4196ee | {
"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 System.Linq;
using SQLite.Net.Attributes;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int? OnlineBeatmapSetID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
public string[] SearchableTerms => new[]
{
Artist,
ArtistUnicode,
Title,
TitleUnicode,
Source,
Tags
}.Where(s => !string.IsNullOrEmpty(s)).ToArray();
}
}```
Add support for searching beatmap author at song select | ```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 System.Linq;
using SQLite.Net.Attributes;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int? OnlineBeatmapSetID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
public string[] SearchableTerms => new[]
{
Author,
Artist,
ArtistUnicode,
Title,
TitleUnicode,
Source,
Tags
}.Where(s => !string.IsNullOrEmpty(s)).ToArray();
}
}``` |
67be4d7f-0751-4b80-8bf3-f575995080e6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SIL.Windows.Forms.Widgets.BetterGrid;
namespace Glyssen.Controls
{
//DataGridView with Enter moving to right (instead of down)
public class DataGridViewOverrideEnter : BetterGrid
{
public DataGridViewOverrideEnter()
{
AllowUserToAddRows = true;
MultiSelect = true;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
MoveToNextField();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
public void MoveToNextField()
{
int nextColumn, nextRow;
if (CurrentCell.ColumnIndex + 1 < ColumnCount)
{
nextColumn = CurrentCell.ColumnIndex + 1;
nextRow = CurrentCell.RowIndex;
}
else
{
nextColumn = 0;
nextRow = CurrentCell.RowIndex + 1;
}
CurrentCell = Rows[nextRow].Cells[nextColumn];
}
private void InitializeComponent()
{
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
}
}
}
```
Fix bug when hitting Enter on last row (PG-234) | ```c#
using System.Windows.Forms;
using SIL.Windows.Forms.Widgets.BetterGrid;
namespace Glyssen.Controls
{
/// <summary>
/// DataGridView with Enter moving to right (instead of down)
/// </summary>
public class DataGridViewOverrideEnter : BetterGrid
{
public DataGridViewOverrideEnter()
{
AllowUserToAddRows = true;
MultiSelect = true;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
MoveToNextField();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
public void MoveToNextField()
{
int nextColumn, nextRow;
if (CurrentCell.ColumnIndex + 1 < ColumnCount)
{
nextColumn = CurrentCell.ColumnIndex + 1;
nextRow = CurrentCell.RowIndex;
}
else if (CurrentCell.RowIndex + 1 < RowCount)
{
nextColumn = 0;
nextRow = CurrentCell.RowIndex + 1;
}
else
{
return;
}
CurrentCell = Rows[nextRow].Cells[nextColumn];
}
}
}
``` |
73eb8767-c4b0-43bd-b5d2-f2b53b548ac9 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpecialPower : MonoBehaviour {
public float manaCost;
public float coolDownDuration;
public string button;
public bool isBomb = false; //tmp
[HideInInspector]
public float mana;
public float maxMana;
public float coolDownTimer = 0;
private ISpecialPower power;
void Start () {
power = GetComponent<ISpecialPower>();
if(!isBomb) {
maxMana = transform.parent.GetComponent<Player>().maxMana; //tmp
}
mana = maxMana;
NotifyUI();
}
// Update is called once per frame
void Update () {
coolDownTimer -= Time.deltaTime;
if(Input.GetButtonDown(button)) {
if (coolDownTimer < 0 && mana >= manaCost) {
power.Activate();
coolDownTimer = coolDownDuration;
mana -= manaCost;
NotifyUI();
}
else {
SoundManager.instance.PlaySound(GenericSoundsEnum.ERROR);
}
}
}
private void NotifyUI() {
if (isBomb) {
BombUI.instance.OnUsePower(this);
}
else {
PowerUI.instance.OnUsePower(this);
}
}
}
```
Fix press space to start game launch bomb | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpecialPower : MonoBehaviour {
public float manaCost;
public float coolDownDuration;
public string button;
public bool isBomb = false; //tmp
[HideInInspector]
public float mana;
public float maxMana;
public float coolDownTimer = 0;
private ISpecialPower power;
void Start () {
power = GetComponent<ISpecialPower>();
if(!isBomb) {
maxMana = transform.parent.GetComponent<Player>().maxMana; //tmp
}
mana = maxMana;
NotifyUI();
enabled = false;
EventDispatcher.AddEventListener(Events.GAME_LOADED, OnLoaded);
}
void OnDestroy() {
EventDispatcher.RemoveEventListener(Events.GAME_LOADED, OnLoaded);
}
private void OnLoaded(object useless) {
enabled = true;
}
// Update is called once per frame
void Update () {
coolDownTimer -= Time.deltaTime;
if(Input.GetButtonDown(button)) {
if (coolDownTimer < 0 && mana >= manaCost) {
power.Activate();
coolDownTimer = coolDownDuration;
mana -= manaCost;
NotifyUI();
}
else {
SoundManager.instance.PlaySound(GenericSoundsEnum.ERROR);
}
}
}
private void NotifyUI() {
if (isBomb) {
BombUI.instance.OnUsePower(this);
}
else {
PowerUI.instance.OnUsePower(this);
}
}
}
``` |
89a66f73-9eea-4de6-80eb-8ebb5e03f2b2 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Graphics.Containers;
using System.Linq;
namespace osu.Framework.Graphics.Performance
{
class PerformanceOverlay : FlowContainer, IStateful<FrameStatisticsMode>
{
private FrameStatisticsMode state;
public FrameStatisticsMode State
{
get
{
return state;
}
set
{
if (state == value) return;
state = value;
switch (state)
{
case FrameStatisticsMode.None:
FadeOut(100);
break;
case FrameStatisticsMode.Minimal:
case FrameStatisticsMode.Full:
FadeIn(100);
foreach (FrameStatisticsDisplay d in Children.Cast<FrameStatisticsDisplay>())
d.State = state;
break;
}
}
}
public override void Load(BaseGame game)
{
base.Load(game);
Add(new FrameStatisticsDisplay(@"Input", game.Host.InputMonitor));
Add(new FrameStatisticsDisplay(@"Update", game.Host.UpdateMonitor));
Add(new FrameStatisticsDisplay(@"Draw", game.Host.DrawMonitor));
Direction = FlowDirection.VerticalOnly;
}
}
public enum FrameStatisticsMode
{
None,
Minimal,
Full
}
}
```
Fix overlay hide animation playing at the wrong point in time. | ```c#
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Graphics.Containers;
using System.Linq;
namespace osu.Framework.Graphics.Performance
{
class PerformanceOverlay : FlowContainer, IStateful<FrameStatisticsMode>
{
private FrameStatisticsMode state;
public FrameStatisticsMode State
{
get
{
return state;
}
set
{
if (state == value) return;
state = value;
switch (state)
{
case FrameStatisticsMode.None:
FadeOut(100);
break;
case FrameStatisticsMode.Minimal:
case FrameStatisticsMode.Full:
FadeIn(100);
break;
}
foreach (FrameStatisticsDisplay d in Children.Cast<FrameStatisticsDisplay>())
d.State = state;
}
}
public override void Load(BaseGame game)
{
base.Load(game);
Add(new FrameStatisticsDisplay(@"Input", game.Host.InputMonitor));
Add(new FrameStatisticsDisplay(@"Update", game.Host.UpdateMonitor));
Add(new FrameStatisticsDisplay(@"Draw", game.Host.DrawMonitor));
Direction = FlowDirection.VerticalOnly;
}
}
public enum FrameStatisticsMode
{
None,
Minimal,
Full
}
}
``` |
5ef11ee6-69de-43c8-a5bd-2e996619047d | {
"language": "C#"
} | ```c#
using AutoMapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace Snittlistan.Installers
{
public class AutoMapperInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(FindProfiles().LifestyleSingleton());
}
private static BasedOnDescriptor FindProfiles()
{
return AllTypes
.FromThisAssembly()
.BasedOn<Profile>();
}
}
}```
Correct installation of AutoMapper profiles | ```c#
using AutoMapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace Snittlistan.Installers
{
public class AutoMapperInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(FindProfiles().LifestyleSingleton().WithServiceFromInterface(typeof(Profile)));
}
private static BasedOnDescriptor FindProfiles()
{
return AllTypes
.FromThisAssembly()
.BasedOn<Profile>();
}
}
}``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.