doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
b81a35d5-f49a-4f52-8179-65f0979b50c3 | {
"language": "C#"
} | ```c#
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace VersionOne.Bugzilla.BugzillaAPI.Testss
{
[TestClass()]
public class given_a_Bug
{
private IBug _bug;
private string _expectedReassignToPayload;
[TestInitialize()]
public void SetContext()
{
_bug = new Bug();
_expectedReassignToPayload = "{\r\n \"assigned_to\": \"denise@denise.com\",\r\n \"status\": \"CONFIRMED\",\r\n \"token\": \"terry.densmore@versionone.com\"\r\n}";
}
[TestMethod]
public void it_should_give_appropriate_reassigneto_payloads()
{
var integrationUser = "terry.densmore@versionone.com";
_bug.AssignedTo = "denise@denise.com";
Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser));
}
}
}
```
Remove no longer needed usings | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace VersionOne.Bugzilla.BugzillaAPI.Testss
{
[TestClass()]
public class given_a_Bug
{
private IBug _bug;
private string _expectedReassignToPayload;
[TestInitialize()]
public void SetContext()
{
_bug = new Bug();
_expectedReassignToPayload = "{\r\n \"assigned_to\": \"denise@denise.com\",\r\n \"status\": \"CONFIRMED\",\r\n \"token\": \"terry.densmore@versionone.com\"\r\n}";
}
[TestMethod]
public void it_should_give_appropriate_reassigneto_payloads()
{
var integrationUser = "terry.densmore@versionone.com";
_bug.AssignedTo = "denise@denise.com";
Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser));
}
}
}
``` |
5a25e5d4-814a-4aa7-900d-1f2ee9b2e91d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Glimpse.Extensions;
namespace Glimpse.Internal
{
public class DefaultMessageTypeProcessor : IMessageTypeProcessor
{
private readonly static Type[] _exclusions = { typeof(object) };
public virtual IEnumerable<string> Derive(object payload)
{
var typeInfo = payload.GetType().GetTypeInfo();
return typeInfo.BaseTypes(true)
.Concat(typeInfo.ImplementedInterfaces)
.Except(_exclusions)
.Select(t => t.KebabCase());
}
}
}```
Drop "-message" from all message names | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Glimpse.Extensions;
namespace Glimpse.Internal
{
public class DefaultMessageTypeProcessor : IMessageTypeProcessor
{
private readonly static Type[] _exclusions = { typeof(object) };
public virtual IEnumerable<string> Derive(object payload)
{
var typeInfo = payload.GetType().GetTypeInfo();
return typeInfo.BaseTypes(true)
.Concat(typeInfo.ImplementedInterfaces)
.Except(_exclusions)
.Select(t =>
{
var result = t.KebabCase();
if (result.EndsWith("-message"))
return result.Substring(0, result.Length - 8);
return result;
});
}
}
}``` |
55ba3d34-8ee6-4b20-985e-d79dfabca51b | {
"language": "C#"
} | ```c#
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
ViewBag.PageID = "authorize-response";
ViewBag.Title = "Please wait";
ViewBag.HideSigninLink = "true";
Layout = "~/Views/Shared/_Layout-NoBanner.cshtml";
}
<h1 class="heading-xlarge">You've logged in</h1>
<form id="mainForm" method="post" action="@Model.ResponseFormUri">
<div id="autoRedirect" style="display: none;">Please wait...</div>
@Html.Raw(Model.ResponseFormFields)
<div id="manualLoginContainer">
<button type="submit" class="button" autofocus="autofocus">Continue</button>
</div>
</form>
@section scripts
{
<script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script>
}```
Use the viewBag Title rather than the hard coded one. | ```c#
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
ViewBag.PageID = "authorize-response";
ViewBag.Title = "Please wait";
ViewBag.HideSigninLink = "true";
Layout = "~/Views/Shared/_Layout-NoBanner.cshtml";
}
<h1 class="heading-xlarge">@ViewBag.Title</h1>
<form id="mainForm" method="post" action="@Model.ResponseFormUri">
<div id="autoRedirect" style="display: none;">Please wait...</div>
@Html.Raw(Model.ResponseFormFields)
<div id="manualLoginContainer">
<button type="submit" class="button" autofocus="autofocus">Continue</button>
</div>
</form>
@section scripts
{
<script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script>
}``` |
622f871b-6efb-405d-8055-eda8490b1fde | {
"language": "C#"
} | ```c#
// Copyright (c) Solal Pirelli 2014
// See License.txt file for more details
using ThinMvvm.WindowsPhone.SampleApp.Resources;
using ThinMvvm.WindowsPhone.SampleApp.ViewModels;
namespace ThinMvvm.WindowsPhone.SampleApp
{
public sealed class App : AppBase
{
protected override string Language
{
get { return AppResources.ResourceLanguage; }
}
protected override string FlowDirection
{
get { return AppResources.ResourceFlowDirection; }
}
public App()
{
Container.Bind<IWindowsPhoneNavigationService, WindowsPhoneNavigationService>();
Container.Bind<ISettingsStorage, WindowsPhoneSettingsStorage>();
Container.Bind<ISettings, Settings>();
}
protected override void Start( AppDependencies dependencies, AppArguments arguments )
{
// simple app, no additional dependencies or arguments
dependencies.NavigationService.Bind<MainViewModel>( "/Views/MainView.xaml" );
dependencies.NavigationService.Bind<AboutViewModel>( "/Views/AboutView.xaml" );
dependencies.NavigationService.NavigateTo<MainViewModel, int>( 42 );
}
}
}```
Fix the sample app following previous changes. | ```c#
// Copyright (c) Solal Pirelli 2014
// See License.txt file for more details
using ThinMvvm.WindowsPhone.SampleApp.Resources;
using ThinMvvm.WindowsPhone.SampleApp.ViewModels;
namespace ThinMvvm.WindowsPhone.SampleApp
{
public sealed class App : AppBase
{
private readonly IWindowsPhoneNavigationService _navigationService;
protected override string Language
{
get { return AppResources.ResourceLanguage; }
}
protected override string FlowDirection
{
get { return AppResources.ResourceFlowDirection; }
}
public App()
{
_navigationService = Container.Bind<IWindowsPhoneNavigationService, WindowsPhoneNavigationService>();
Container.Bind<ISettingsStorage, WindowsPhoneSettingsStorage>();
Container.Bind<ISettings, Settings>();
}
protected override void Start( AppArguments arguments )
{
// simple app, no additional dependencies or arguments
_navigationService.Bind<MainViewModel>( "/Views/MainView.xaml" );
_navigationService.Bind<AboutViewModel>( "/Views/AboutView.xaml" );
_navigationService.NavigateTo<MainViewModel, int>( 42 );
}
}
}``` |
15d6a7ef-e194-452a-a804-60b4302269cc | {
"language": "C#"
} | ```c#
namespace Bakery.Security
{
using System;
public static class RandomExtensions
{
public static Byte[] GetBytes(this IRandom random, Int32 count)
{
if (count <= 0)
throw new ArgumentOutOfRangeException(nameof(count));
var buffer = new Byte[count];
for (var i = 0; i < count; i++)
buffer[i] = random.GetByte();
return buffer;
}
public static Int64 GetInt64(this IRandom random)
{
return BitConverter.ToInt64(random.GetBytes(8), 0);
}
}
}
```
Add extension method for IRandom to get an unsigned 64-bit integer. | ```c#
namespace Bakery.Security
{
using System;
public static class RandomExtensions
{
public static Byte[] GetBytes(this IRandom random, Int32 count)
{
if (count <= 0)
throw new ArgumentOutOfRangeException(nameof(count));
var buffer = new Byte[count];
for (var i = 0; i < count; i++)
buffer[i] = random.GetByte();
return buffer;
}
public static Int64 GetInt64(this IRandom random)
{
return BitConverter.ToInt64(random.GetBytes(8), 0);
}
public static UInt64 GetUInt64(this IRandom random)
{
return BitConverter.ToUInt64(random.GetBytes(8), 0);
}
}
}
``` |
bdb2b67d-47d2-4bbd-8f23-480aee8e53e9 | {
"language": "C#"
} | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickImageTests
{
public class TheAddNoiseMethod
{
[Fact]
public void ShouldCreateDifferentImagesEachRun()
{
using (var imageA = new MagickImage(MagickColors.Black, 100, 100))
{
imageA.AddNoise(NoiseType.Random);
using (var imageB = new MagickImage(MagickColors.Black, 100, 100))
{
imageB.AddNoise(NoiseType.Random);
Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared));
}
}
}
}
}
}
```
Revert changes to the test. | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickImageTests
{
public class TheAddNoiseMethod
{
[Fact]
public void ShouldCreateDifferentImagesEachRun()
{
using (var imageA = new MagickImage(MagickColors.Black, 10, 10))
{
using (var imageB = new MagickImage(MagickColors.Black, 10, 10))
{
imageA.AddNoise(NoiseType.Random);
imageB.AddNoise(NoiseType.Random);
Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared));
}
}
}
}
}
}
``` |
82b53c7d-02b0-4a32-8971-236450e95653 | {
"language": "C#"
} | ```c#
using IntegrationEngine.Api.Controllers;
using IntegrationEngine.Core.Storage;
using IntegrationEngine.Model;
using IntegrationEngine.Scheduler;
using Moq;
using NUnit.Framework;
namespace IntegrationEngine.Tests.Api.Controllers
{
public class CronTriggerControllerTest
{
[Test]
public void ShouldScheduleJobWhenCronTriggerIsCreated()
{
var subject = new CronTriggerController();
var cronExpression = "0 6 * * 1-5";
var jobType = "MyProject.MyIntegrationJob";
var expected = new CronTrigger() {
JobType = jobType,
CronExpressionString = cronExpression
};
var engineScheduler = new Mock<IEngineScheduler>();
engineScheduler.Setup(x => x.ScheduleJobWithCronTrigger(expected));
subject.EngineScheduler = engineScheduler.Object;
var esRepository = new Mock<ESRepository<CronTrigger>>();
esRepository.Setup(x => x.Insert(expected)).Returns(expected);
subject.Repository = esRepository.Object;
subject.PostCronTrigger(expected);
engineScheduler.Verify(x => x
.ScheduleJobWithCronTrigger(It.Is<CronTrigger>(y => y.JobType == jobType &&
y.CronExpressionString == cronExpression)), Times.Once);
}
}
}
```
Add valid cron expression to test | ```c#
using IntegrationEngine.Api.Controllers;
using IntegrationEngine.Core.Storage;
using IntegrationEngine.Model;
using IntegrationEngine.Scheduler;
using Moq;
using NUnit.Framework;
namespace IntegrationEngine.Tests.Api.Controllers
{
public class CronTriggerControllerTest
{
[Test]
public void ShouldScheduleJobWhenCronTriggerIsCreatedWithValidCronExpression()
{
var subject = new CronTriggerController();
var cronExpression = "0 6 * * 1-5 ?";
var jobType = "MyProject.MyIntegrationJob";
var expected = new CronTrigger() {
JobType = jobType,
CronExpressionString = cronExpression
};
var engineScheduler = new Mock<IEngineScheduler>();
engineScheduler.Setup(x => x.ScheduleJobWithCronTrigger(expected));
subject.EngineScheduler = engineScheduler.Object;
var esRepository = new Mock<ESRepository<CronTrigger>>();
esRepository.Setup(x => x.Insert(expected)).Returns(expected);
subject.Repository = esRepository.Object;
subject.PostCronTrigger(expected);
engineScheduler.Verify(x => x
.ScheduleJobWithCronTrigger(It.Is<CronTrigger>(y => y.JobType == jobType &&
y.CronExpressionString == cronExpression)), Times.Once);
}
}
}
``` |
4b318426-c2cc-41a4-8a13-d8859c6ed564 | {
"language": "C#"
} | ```c#
namespace TestHttpCompositionConsoleApp
{
using Serviceable.Objects.Remote.Composition.Host;
using Serviceable.Objects.Remote.Composition.Host.Commands;
class Program
{
static void Main(string[] args)
{
/*
* Principles:
*
* Testable
* Composable
* Configurable
* Instrumentable
* Scalable
* Updatable TODO
*
*/
new ApplicationHost(args).Execute(new RunAndBlock());
}
}
}```
Add some comments for the host process | ```c#
namespace TestHttpCompositionConsoleApp
{
using Serviceable.Objects.Remote.Composition.Host;
using Serviceable.Objects.Remote.Composition.Host.Commands;
class Program
{
static void Main(string[] args)
{
/*
* Principles:
*
* Testable
* Composable
* Configurable
* Instrumentable
* Scalable
* Updatable TODO
*
*/
// Sample host should minimal like that.
// Override templates or data from args before reaching the host execution
new ApplicationHost(args).Execute(new RunAndBlock());
}
}
}``` |
0f9c1c3d-0f38-4873-af88-df4ac95f7d47 | {
"language": "C#"
} | ```c#
@using Orchard.Mvc.Html;
@{
Layout.Title = T("New Blog");
}
<div class="edit-item">
<div class="edit-item-primary">
@if (Model.Content != null) {
<div class="edit-item-content">
@Display(Model.Content)
</div>
}
</div>
<div class="edit-item-secondary group">
@if (Model.Actions != null) {
<div class="edit-item-actions">
@Display(Model.Actions)
</div>
}
@if (Model.Sidebar != null) {
<div class="edit-item-sidebar group">
@Display(Model.Sidebar)
</div>
}
</div>
</div>```
Fix incorrect title on edit page | ```c#
@using Orchard.Mvc.Html;
<div class="edit-item">
<div class="edit-item-primary">
@if (Model.Content != null) {
<div class="edit-item-content">
@Display(Model.Content)
</div>
}
</div>
<div class="edit-item-secondary group">
@if (Model.Actions != null) {
<div class="edit-item-actions">
@Display(Model.Actions)
</div>
}
@if (Model.Sidebar != null) {
<div class="edit-item-sidebar group">
@Display(Model.Sidebar)
</div>
}
</div>
</div>
``` |
54ce1f05-73e5-4e74-b7ce-d317f8fda11c | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using SurveyMonkey.RequestSettings;
namespace SurveyMonkey.Helpers
{
internal class RequestSettingsHelper
{
internal static RequestData GetPopulatedProperties(object obj)
{
var output = new RequestData();
foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
if (property.GetValue(obj, null) != null)
{
Type underlyingType = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
? Nullable.GetUnderlyingType(property.PropertyType)
: property.PropertyType;
if (underlyingType.IsEnum)
{
output.Add(PropertyCasingHelper.CamelToSnake(property.Name), PropertyCasingHelper.CamelToSnake(property.GetValue(obj, null).ToString()));
}
else if (underlyingType == typeof(DateTime))
{
output.Add(PropertyCasingHelper.CamelToSnake(property.Name), ((DateTime)property.GetValue(obj, null)).ToString("s"));
}
else
{
output.Add(PropertyCasingHelper.CamelToSnake(property.Name), property.GetValue(obj, null));
}
}
}
return output;
}
}
}```
Format dates properly for the api | ```c#
using System;
using System.Reflection;
using SurveyMonkey.RequestSettings;
namespace SurveyMonkey.Helpers
{
internal class RequestSettingsHelper
{
internal static RequestData GetPopulatedProperties(object obj)
{
var output = new RequestData();
foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
if (property.GetValue(obj, null) != null)
{
Type underlyingType = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
? Nullable.GetUnderlyingType(property.PropertyType)
: property.PropertyType;
if (underlyingType.IsEnum)
{
output.Add(PropertyCasingHelper.CamelToSnake(property.Name), PropertyCasingHelper.CamelToSnake(property.GetValue(obj, null).ToString()));
}
else if (underlyingType == typeof(DateTime))
{
output.Add(PropertyCasingHelper.CamelToSnake(property.Name), ((DateTime)property.GetValue(obj, null)).ToString("s") + "+00:00");
}
else
{
output.Add(PropertyCasingHelper.CamelToSnake(property.Name), property.GetValue(obj, null));
}
}
}
return output;
}
}
}``` |
8ec9d383-bada-477d-b816-5e8c983be2f7 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Raven.Bundles.Contrib.IndexedAttachments")]
[assembly: AssemblyDescription("Plugin for RavenDB that extracts text from attachments so they can be indexed.")]
[assembly: AssemblyVersion("2.0.2.0")]
[assembly: AssemblyFileVersion("2.0.2.0")]
```
Set IndexedAttachments to version 2.0.3.0 | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Raven.Bundles.Contrib.IndexedAttachments")]
[assembly: AssemblyDescription("Plugin for RavenDB that extracts text from attachments so they can be indexed.")]
[assembly: AssemblyVersion("2.0.3.0")]
[assembly: AssemblyFileVersion("2.0.3.0")]
``` |
c328b3ac-1c14-423d-b265-3566917346d8 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace Konsola.Metadata
{
public class ObjectMetadata
{
public ObjectMetadata(
Type type,
IEnumerable<PropertyMetadata> properties,
IEnumerable<AttributeMetadata> attributes)
{
Type = type;
Properties = properties;
Attributes = attributes;
}
public Type Type { get; private set; }
public virtual IEnumerable<PropertyMetadata> Properties { get; private set; }
public virtual IEnumerable<AttributeMetadata> Attributes { get; private set; }
}
}```
Add helpers for finding attributes | ```c#
using System;
using System.Linq;
using System.Collections.Generic;
namespace Konsola.Metadata
{
public class ObjectMetadata
{
public ObjectMetadata(
Type type,
IEnumerable<PropertyMetadata> properties,
IEnumerable<AttributeMetadata> attributes)
{
Type = type;
Properties = properties;
Attributes = attributes;
}
public Type Type { get; private set; }
public virtual IEnumerable<PropertyMetadata> Properties { get; private set; }
public virtual IEnumerable<AttributeMetadata> Attributes { get; private set; }
public IEnumerable<T> AttributesOfType<T>()
{
return
Attributes
.Select(a => a.Attribute)
.OfType<T>();
}
public T AttributeOfType<T>()
{
return
AttributesOfType<T>()
.FirstOrDefault();
}
}
}``` |
db38a86e-934c-4310-acb9-e372b8407c7f | {
"language": "C#"
} | ```c#
/*
* Copyright (c) 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
// [START bigquery_data_transfer_quickstart]
using System;
using Google.Api.Gax;
using Google.Cloud.BigQuery.DataTransfer.V1;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// Instantiates a client
DataTransferServiceClient client = DataTransferServiceClient.Create();
// Your Google Cloud Platform project ID
string projectId = "YOUR-PROJECT-ID";
ProjectName project = new ProjectName(projectId);
var sources = client.ListDataSources(ParentNameOneof.From(project));
Console.WriteLine("Supported Data Sources:");
foreach (DataSource source in sources)
{
Console.WriteLine(
$"{source.DataSourceId}: " +
$"{source.DisplayName} ({source.Description})");
}
}
}
}
// [END bigquery_data_transfer_quickstart]
```
Use bigquerydatatransfer instead of bigquery_data_transfer in region tags | ```c#
/*
* Copyright (c) 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
// [START bigquerydatatransfer_quickstart]
using System;
using Google.Api.Gax;
using Google.Cloud.BigQuery.DataTransfer.V1;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// Instantiates a client
DataTransferServiceClient client = DataTransferServiceClient.Create();
// Your Google Cloud Platform project ID
string projectId = "YOUR-PROJECT-ID";
ProjectName project = new ProjectName(projectId);
var sources = client.ListDataSources(ParentNameOneof.From(project));
Console.WriteLine("Supported Data Sources:");
foreach (DataSource source in sources)
{
Console.WriteLine(
$"{source.DataSourceId}: " +
$"{source.DisplayName} ({source.Description})");
}
}
}
}
// [END bigquerydatatransfer_quickstart]
``` |
1fa2aeb9-4975-4914-92f1-7a70e87eb9ed | {
"language": "C#"
} | ```c#
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using LiberisLabs.CompaniesHouse.Response.CompanyProfile;
using LiberisLabs.CompaniesHouse.UriBuilders;
namespace LiberisLabs.CompaniesHouse
{
public class CompaniesHouseCompanyProfileClient : ICompaniesHouseCompanyProfileClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ICompanyProfileUriBuilder _companyProfileUriBuilder;
public CompaniesHouseCompanyProfileClient(IHttpClientFactory httpClientFactory, ICompanyProfileUriBuilder companyProfileUriBuilder)
{
_httpClientFactory = httpClientFactory;
_companyProfileUriBuilder = companyProfileUriBuilder;
}
public async Task<CompaniesHouseClientResponse<CompanyProfile>> GetCompanyProfileAsync(string companyNumber, CancellationToken cancellationToken = default(CancellationToken))
{
using (var httpClient = _httpClientFactory.CreateHttpClient())
{
var requestUri = _companyProfileUriBuilder.Build(companyNumber);
var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);
CompanyProfile result = response.IsSuccessStatusCode
? await response.Content.ReadAsAsync<CompanyProfile>(cancellationToken).ConfigureAwait(false)
: null;
return new CompaniesHouseClientResponse<CompanyProfile>(result);
}
}
}
}```
Raise exceptions on non-404 error codes | ```c#
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using LiberisLabs.CompaniesHouse.Response.CompanyProfile;
using LiberisLabs.CompaniesHouse.UriBuilders;
namespace LiberisLabs.CompaniesHouse
{
public class CompaniesHouseCompanyProfileClient : ICompaniesHouseCompanyProfileClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ICompanyProfileUriBuilder _companyProfileUriBuilder;
public CompaniesHouseCompanyProfileClient(IHttpClientFactory httpClientFactory, ICompanyProfileUriBuilder companyProfileUriBuilder)
{
_httpClientFactory = httpClientFactory;
_companyProfileUriBuilder = companyProfileUriBuilder;
}
public async Task<CompaniesHouseClientResponse<CompanyProfile>> GetCompanyProfileAsync(string companyNumber, CancellationToken cancellationToken = default(CancellationToken))
{
using (var httpClient = _httpClientFactory.CreateHttpClient())
{
var requestUri = _companyProfileUriBuilder.Build(companyNumber);
var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);
// Return a null profile on 404s, but raise exception for all other error codes
if (response.StatusCode != System.Net.HttpStatusCode.NotFound)
response.EnsureSuccessStatusCode();
CompanyProfile result = response.IsSuccessStatusCode
? await response.Content.ReadAsAsync<CompanyProfile>(cancellationToken).ConfigureAwait(false)
: null;
return new CompaniesHouseClientResponse<CompanyProfile>(result);
}
}
}
}``` |
c27893e2-b19a-4a21-a56b-24188311c74e | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using BundlerMiddleware;
[assembly: OwinStartup(typeof(BundlerTestSite.Startup))]
namespace BundlerTestSite
{
public class Startup
{
public static BundlerRouteTable MarkdownRoutes = new BundlerRouteTable();
public static BundlerRouteTable MarkdownRoutesWithTemplate = new BundlerRouteTable();
public void Configuration(IAppBuilder app)
{
app.UseBundlerMiddlewareForIIS();
app.UseBundlerMarkdown(MarkdownRoutes);
app.UseBundlerMarkdownWithTempalte("~/markdown/markdowntemplate.html", MarkdownRoutesWithTemplate);
}
}
}
```
Fix tabs/spaces in test site startup | ```c#
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using BundlerMiddleware;
[assembly: OwinStartup(typeof(BundlerTestSite.Startup))]
namespace BundlerTestSite
{
public class Startup
{
public static BundlerRouteTable MarkdownRoutes = new BundlerRouteTable();
public static BundlerRouteTable MarkdownRoutesWithTemplate = new BundlerRouteTable();
public void Configuration(IAppBuilder app)
{
app.UseBundlerMiddlewareForIIS();
app.UseBundlerMarkdown(MarkdownRoutes);
app.UseBundlerMarkdownWithTempalte("~/markdown/markdowntemplate.html", MarkdownRoutesWithTemplate);
}
}
}
``` |
9bf8d732-0ecf-4214-87d3-a76f11a403d2 | {
"language": "C#"
} | ```c#
// Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using CorrugatedIron.Tests.Live.LiveRiakConnectionTests;
using NUnit.Framework;
namespace CorrugatedIron.Tests.Live
{
[TestFixture]
public class RiakDtTests : LiveRiakConnectionTestBase
{
private const string Bucket = "riak_dt_bucket";
[TearDown]
public void TearDown()
{
Client.DeleteBucket(Bucket);
}
}
}
```
Test commit of new line endings | ```c#
// Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using CorrugatedIron.Tests.Live.LiveRiakConnectionTests;
using NUnit.Framework;
namespace CorrugatedIron.Tests.Live
{
[TestFixture]
public class RiakDtTests : LiveRiakConnectionTestBase
{
private const string Bucket = "riak_dt_bucket";
/// <summary>
/// The tearing of the down, it is done here.
/// </summary>
[TearDown]
public void TearDown()
{
Client.DeleteBucket(Bucket);
}
}
}
``` |
b85c96e9-a033-4e34-8457-3a282f7425f3 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mindscape.Raygun4Net
{
public class RaygunClientBase
{
protected internal const string SentKey = "AlreadySentByRaygun";
protected bool CanSend(Exception exception)
{
return exception == null || !exception.Data.Contains(SentKey) || false.Equals(exception.Data[SentKey]);
}
protected void FlagAsSent(Exception exception)
{
if (exception != null)
{
exception.Data[SentKey] = true;
}
}
}
}
```
Check that Data dictionary accepts string keys. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mindscape.Raygun4Net
{
public class RaygunClientBase
{
protected internal const string SentKey = "AlreadySentByRaygun";
protected bool CanSend(Exception exception)
{
return exception == null || exception.Data == null || !exception.Data.Contains(SentKey) || false.Equals(exception.Data[SentKey]);
}
protected void FlagAsSent(Exception exception)
{
if (exception != null && exception.Data != null)
{
try
{
Type[] genericTypes = exception.Data.GetType().GetGenericArguments();
if (genericTypes.Length > 0 && genericTypes[0].IsAssignableFrom(typeof(string)))
{
exception.Data[SentKey] = true;
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(String.Format("Failed to flag exception as sent: {0}", ex.Message));
}
}
}
}
}
``` |
eb1bd4b4-4957-4195-bbe7-d227502c7ea0 | {
"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.Online.Multiplayer;
using osu.Game.Online.Multiplayer.RoomStatuses;
using osu.Game.Screens.Multi.Lounge.Components;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneRoomStatus : OsuTestScene
{
public TestSceneRoomStatus()
{
Child = new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Width = 0.5f,
Children = new Drawable[]
{
new DrawableRoom(new Room
{
Name = { Value = "Room 1" },
Status = { Value = new RoomStatusOpen() }
}),
new DrawableRoom(new Room
{
Name = { Value = "Room 2" },
Status = { Value = new RoomStatusPlaying() }
}),
new DrawableRoom(new Room
{
Name = { Value = "Room 3" },
Status = { Value = new RoomStatusEnded() }
}),
}
};
}
}
}
```
Fix room status test scene not working | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Multiplayer.RoomStatuses;
using osu.Game.Screens.Multi.Lounge.Components;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneRoomStatus : OsuTestScene
{
public TestSceneRoomStatus()
{
Child = new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Width = 0.5f,
Children = new Drawable[]
{
new DrawableRoom(new Room
{
Name = { Value = "Room 1" },
Status = { Value = new RoomStatusOpen() },
EndDate = { Value = DateTimeOffset.Now.AddDays(1) }
}) { MatchingFilter = true },
new DrawableRoom(new Room
{
Name = { Value = "Room 2" },
Status = { Value = new RoomStatusPlaying() },
EndDate = { Value = DateTimeOffset.Now.AddDays(1) }
}) { MatchingFilter = true },
new DrawableRoom(new Room
{
Name = { Value = "Room 3" },
Status = { Value = new RoomStatusEnded() },
EndDate = { Value = DateTimeOffset.Now }
}) { MatchingFilter = true },
}
};
}
}
}
``` |
006da4a8-eda3-46ea-9a78-6514495dc806 | {
"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.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class GetBeatmapRequest : APIRequest<APIBeatmap>
{
private readonly BeatmapInfo beatmap;
public GetBeatmapRequest(BeatmapInfo beatmap)
{
this.beatmap = beatmap;
}
protected override string Target => $@"beatmaps/lookup?id={beatmap.OnlineBeatmapID}&checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}";
}
}
```
Fix beatmap lookups failing for beatmaps with no local path | ```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.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class GetBeatmapRequest : APIRequest<APIBeatmap>
{
private readonly BeatmapInfo beatmap;
public GetBeatmapRequest(BeatmapInfo beatmap)
{
this.beatmap = beatmap;
}
protected override string Target => $@"beatmaps/lookup?id={beatmap.OnlineBeatmapID}&checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path ?? string.Empty)}";
}
}
``` |
1eb9aaf8-444d-43ce-909e-815674ae1c66 | {
"language": "C#"
} | ```c#
using System.Linq;
using NakedFunctions;
namespace AW
{
public static class Helpers
{
/// <summary>
/// Returns a random instance from the set of all instance of type T
/// </summary>
public static T Random<T>(IContext context) where T : class
{
//The OrderBy(...) doesn't change the ordering, but is a necessary precursor to using .Skip
//which in turn is needed because LINQ to Entities doesn't support .ElementAt(x)
var instances = context.Instances<T>().OrderBy(n => "");
return instances.Skip(context.RandomSeed().ValueInRange(instances.Count())).FirstOrDefault();
}
}
}```
Add temp dummy impl of IContext.WithDeleted and WithFunction | ```c#
using System;
using System.Linq;
using NakedFunctions;
namespace AW
{
public static class Helpers
{
/// <summary>
/// Returns a random instance from the set of all instance of type T
/// </summary>
public static T Random<T>(IContext context) where T : class
{
//The OrderBy(...) doesn't change the ordering, but is a necessary precursor to using .Skip
//which in turn is needed because LINQ to Entities doesn't support .ElementAt(x)
var instances = context.Instances<T>().OrderBy(n => "");
return instances.Skip(context.RandomSeed().ValueInRange(instances.Count())).FirstOrDefault();
}
//TODO: Temporary DUMMY extension method, pending native new method on IContext.
public static IContext WithFunction(this IContext context, Func<IContext, IContext> func) =>
context.WithInformUser($"Registered function {func.ToString()} NOT called.");
//TODO: Temporary DUMMY extension method, pending native new method on IContext.
public static IContext WithDeleted(this IContext context, object toDelete) =>
context.WithInformUser($"object {toDelete} scheduled for deletion.");
}
}``` |
9b3cfb96-4483-44e2-9986-348e2bee07a4 | {
"language": "C#"
} | ```c#
using System.IO;
using Arkivverket.Arkade.Core.Base;
using Arkivverket.Arkade.GUI.Properties;
namespace Arkivverket.Arkade.GUI.Util
{
public static class ArkadeProcessingAreaLocationSetting
{
public static string Get()
{
Settings.Default.Reload();
return Settings.Default.ArkadeProcessingAreaLocation;
}
public static void Set(string locationSetting)
{
Settings.Default.ArkadeProcessingAreaLocation = locationSetting;
Settings.Default.Save();
}
public static bool IsValid()
{
try
{
string definedLocation = Get();
return DirectoryIsWritable(definedLocation);
}
catch
{
return false; // Invalid path string in settings
}
}
public static bool IsApplied()
{
string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty;
string definedLocation = Get();
return appliedLocation.Equals(definedLocation);
}
private static bool DirectoryIsWritable(string directory)
{
string tmpFile = Path.Combine(directory, Path.GetRandomFileName());
try
{
using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose))
{
// Attempt to write temporary file to the directory
}
return true;
}
catch
{
return false;
}
}
}
}
```
Make sure ProcessAreaLocationSetting is set on first start-up | ```c#
using System.IO;
using Arkivverket.Arkade.Core.Base;
using Arkivverket.Arkade.GUI.Properties;
namespace Arkivverket.Arkade.GUI.Util
{
public static class ArkadeProcessingAreaLocationSetting
{
public static string Get()
{
Settings.Default.Reload();
return Settings.Default.ArkadeProcessingAreaLocation;
}
public static void Set(string locationSetting)
{
Settings.Default.ArkadeProcessingAreaLocation = locationSetting;
Settings.Default.Save();
}
public static bool IsValid()
{
try
{
string definedLocation = Get();
return DirectoryIsWritable(definedLocation);
}
catch
{
return false; // Invalid path string in settings
}
}
public static bool IsApplied()
{
string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty;
string definedLocation = Get();
return appliedLocation.Equals(definedLocation);
}
private static bool DirectoryIsWritable(string directory)
{
if (string.IsNullOrWhiteSpace(directory))
return false;
string tmpFile = Path.Combine(directory, Path.GetRandomFileName());
try
{
using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose))
{
// Attempt to write temporary file to the directory
}
return true;
}
catch
{
return false;
}
}
}
}
``` |
e9bf838d-d9ad-45db-a30c-be688df320bb | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomWalkConsole
{
class Program
{
static void Main(string[] args)
{
}
}
}
```
Implement random walk for 2D | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace RandomWalkConsole
{
class Program
{
static void Main(string[] args)
{
var unfinished = Enumerable.Range(0, 1000)
.Select(_ => Walk2())
.Aggregate(0, (u, t) => u + (t.HasValue ? 0 : 1));
Console.WriteLine(unfinished);
}
static readonly Random random = new Random();
static readonly Int32Vector3[] Directions2 = new[] { Int32Vector3.XBasis, Int32Vector3.YBasis, -Int32Vector3.XBasis, -Int32Vector3.YBasis };
static int? Walk2()
{
var current = Int32Vector3.Zero;
for (var i = 1; i <= 1000000; i++)
{
current += Directions2[random.Next(0, Directions2.Length)];
if (current == Int32Vector3.Zero) return i;
}
Console.WriteLine(current);
return null;
}
}
}
``` |
509756e8-baf6-4ac6-b335-6bd5c073396f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Dashboard
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
Switch to lower case URLs | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Dashboard
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
``` |
a7d5b912-f9c8-4845-b665-1e534816c093 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGameUtils.Drawing
{
/// <summary>
/// Various useful utility methods that don't obviously go elsewhere.
/// </summary>
public static class Utilities
{
/// <summary>
/// Draw the provided model in the world, given the provided matrices.
/// </summary>
/// <param name="model">The model to draw.</param>
/// <param name="world">The world matrix that the model should be drawn in.</param>
/// <param name="view">The view matrix that the model should be drawn in.</param>
/// <param name="projection">The projection matrix that the model should be drawn in.</param>
private static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = world;
effect.View = view;
effect.Projection = projection;
}
mesh.Draw();
}
}
}
}```
Make public a method which was accidentally committed as private. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGameUtils.Drawing
{
/// <summary>
/// Various useful utility methods that don't obviously go elsewhere.
/// </summary>
public static class Utilities
{
/// <summary>
/// Draw the provided model in the world, given the provided matrices.
/// </summary>
/// <param name="model">The model to draw.</param>
/// <param name="world">The world matrix that the model should be drawn in.</param>
/// <param name="view">The view matrix that the model should be drawn in.</param>
/// <param name="projection">The projection matrix that the model should be drawn in.</param>
public static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = world;
effect.View = view;
effect.Projection = projection;
}
mesh.Draw();
}
}
}
}``` |
25697d1a-2f9e-489a-a213-889ef532bf53 | {
"language": "C#"
} | ```c#
// Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using System;
using System.Linq;
namespace AppBrix.Events.Schedule.Impl
{
internal abstract class PriorityQueueItem
{
#region Construction
public PriorityQueueItem(object scheduledEvent)
{
this.ScheduledEvent = scheduledEvent;
}
#endregion
#region Properties
public object ScheduledEvent { get; }
public DateTime Occurrence { get; protected set; }
#endregion
#region Public and overriden methods
public abstract void Execute();
public abstract void MoveToNextOccurrence(DateTime now);
#endregion
}
internal sealed class PriorityQueueItem<T> : PriorityQueueItem where T : IEvent
{
#region Construction
public PriorityQueueItem(IApp app, IScheduledEvent<T> scheduledEvent)
: base(scheduledEvent)
{
this.app = app;
this.scheduledEvent = scheduledEvent;
}
#endregion
#region Public and overriden methods
public override void Execute()
{
try
{
this.app.GetEventHub().Raise(this.scheduledEvent.Event);
}
catch (Exception)
{
}
}
public override void MoveToNextOccurrence(DateTime now)
{
this.Occurrence = ((IScheduledEvent<T>)this.ScheduledEvent).GetNextOccurrence(now);
}
#endregion
#region Private fields and constants
private readonly IApp app;
private readonly IScheduledEvent<T> scheduledEvent;
#endregion
}
}
```
Remove unnecessary reference to IScheduledEvent | ```c#
// Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using System;
using System.Linq;
namespace AppBrix.Events.Schedule.Impl
{
internal abstract class PriorityQueueItem
{
#region Properties
public abstract object ScheduledEvent { get; }
public DateTime Occurrence { get; protected set; }
#endregion
#region Public and overriden methods
public abstract void Execute();
public abstract void MoveToNextOccurrence(DateTime now);
#endregion
}
internal sealed class PriorityQueueItem<T> : PriorityQueueItem where T : IEvent
{
#region Construction
public PriorityQueueItem(IApp app, IScheduledEvent<T> scheduledEvent)
{
this.app = app;
this.scheduledEvent = scheduledEvent;
}
#endregion
#region Properties
public override object ScheduledEvent => this.scheduledEvent;
#endregion
#region Public and overriden methods
public override void Execute()
{
try
{
this.app.GetEventHub().Raise(this.scheduledEvent.Event);
}
catch (Exception)
{
}
}
public override void MoveToNextOccurrence(DateTime now)
{
this.Occurrence = this.scheduledEvent.GetNextOccurrence(now);
}
#endregion
#region Private fields and constants
private readonly IApp app;
private readonly IScheduledEvent<T> scheduledEvent;
#endregion
}
}
``` |
80b3c7f3-2a15-44fa-bf39-2a8605bff2b4 | {
"language": "C#"
} | ```c#
using System.Web.Mvc;
namespace RightpointLabs.Pourcast.Web.Controllers
{
using RightpointLabs.Pourcast.Application.Orchestrators.Abstract;
public class HomeController : Controller
{
private readonly ITapOrchestrator _tapOrchestrator;
private readonly IIdentityOrchestrator _identityOrchestrator;
public HomeController(ITapOrchestrator tapOrchestrator, IIdentityOrchestrator identityOrchestrator)
{
_tapOrchestrator = tapOrchestrator;
_identityOrchestrator = identityOrchestrator;
}
//
// GET: /Home/
public ActionResult Index()
{
// Replace this with a Mock so it doesn't blow up the app
//_tapOrchestrator.PourBeerFromTap("534a14b1aed2bf2a00045509", .01);
// TODO : remove this so users aren't added to admin automatically!
var roleName = "Administrators";
var username = Request.LogonUserIdentity.Name;
if (!_identityOrchestrator.UserExists(username))
{
_identityOrchestrator.CreateUser(username);
}
if (!_identityOrchestrator.RoleExists(roleName))
{
_identityOrchestrator.CreateRole(roleName);
}
if (!_identityOrchestrator.IsUserInRole(username, roleName))
{
_identityOrchestrator.AddUserToRole(username, roleName);
}
return View();
}
}
}```
Kill auto user insertion in non-debug | ```c#
using System.Web.Mvc;
namespace RightpointLabs.Pourcast.Web.Controllers
{
using RightpointLabs.Pourcast.Application.Orchestrators.Abstract;
public class HomeController : Controller
{
private readonly ITapOrchestrator _tapOrchestrator;
private readonly IIdentityOrchestrator _identityOrchestrator;
public HomeController(ITapOrchestrator tapOrchestrator, IIdentityOrchestrator identityOrchestrator)
{
_tapOrchestrator = tapOrchestrator;
_identityOrchestrator = identityOrchestrator;
}
//
// GET: /Home/
public ActionResult Index()
{
// Replace this with a Mock so it doesn't blow up the app
//_tapOrchestrator.PourBeerFromTap("534a14b1aed2bf2a00045509", .01);
#if DEBUG
// TODO : remove this so users aren't added to admin automatically!
var roleName = "Administrators";
var username = Request.LogonUserIdentity.Name;
if (!_identityOrchestrator.UserExists(username))
{
_identityOrchestrator.CreateUser(username);
}
if (!_identityOrchestrator.RoleExists(roleName))
{
_identityOrchestrator.CreateRole(roleName);
}
if (!_identityOrchestrator.IsUserInRole(username, roleName))
{
_identityOrchestrator.AddUserToRole(username, roleName);
}
#endif
return View();
}
}
}``` |
66c32e27-70fc-47ed-94de-11649d284983 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Verdeler
{
internal class MultipleConcurrencyLimiter<TSubject>
{
private readonly List<ConcurrencyLimiter<TSubject>> _concurrencyLimiters =
new List<ConcurrencyLimiter<TSubject>>();
public void AddConcurrencyLimiter(Func<TSubject, object> reductionMap, int number)
{
_concurrencyLimiters.Add(new ConcurrencyLimiter<TSubject>(reductionMap, number));
}
public async Task Do(Func<Task> asyncFunc, TSubject subject)
{
//NOTE: This cannot be replaced with a Linq .ForEach
foreach (var cl in _concurrencyLimiters)
{
await cl.WaitFor(subject).ConfigureAwait(false);
}
try
{
await asyncFunc().ConfigureAwait(false);
}
finally
{
//Release in the reverse order to prevent deadlocks
_concurrencyLimiters
.AsEnumerable().Reverse().ToList()
.ForEach(l => l.Release(subject));
}
}
}
}
```
Update comments & variable name | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Verdeler
{
internal class MultipleConcurrencyLimiter<TSubject>
{
private readonly List<ConcurrencyLimiter<TSubject>> _concurrencyLimiters =
new List<ConcurrencyLimiter<TSubject>>();
public void AddConcurrencyLimiter(Func<TSubject, object> reductionMap, int number)
{
_concurrencyLimiters.Add(new ConcurrencyLimiter<TSubject>(reductionMap, number));
}
public async Task Do(Func<Task> asyncFunc, TSubject subject)
{
//We must obtain locks in order to prevent cycles from forming.
foreach (var concurrencyLimiter in _concurrencyLimiters)
{
await concurrencyLimiter.WaitFor(subject).ConfigureAwait(false);
}
try
{
await asyncFunc().ConfigureAwait(false);
}
finally
{
//Release in reverse order
_concurrencyLimiters
.AsEnumerable().Reverse().ToList()
.ForEach(l => l.Release(subject));
}
}
}
}
``` |
1c993782-f333-4fe1-ac86-4462b27ce021 | {
"language": "C#"
} | ```c#
// -----------------------------------------------------------------------
// <copyright file="RemotingSystem.cs" company="Asynkron HB">
// Copyright (C) 2015-2017 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using Grpc.Core;
namespace Proto.Remote
{
public static class RemotingSystem
{
private static Server _server;
public static PID EndpointManagerPid { get; private set; }
public static void Start(string host, int port)
{
var addr = host + ":" + port;
ProcessRegistry.Instance.Address = addr;
ProcessRegistry.Instance.RegisterHostResolver(pid => new RemoteProcess(pid));
_server = new Server
{
Services = {Remoting.BindService(new EndpointReader())},
Ports = {new ServerPort(host, port, ServerCredentials.Insecure)}
};
_server.Start();
var emProps =
Actor.FromProducer(() => new EndpointManager());
EndpointManagerPid = Actor.Spawn(emProps);
Console.WriteLine($"[REMOTING] Starting Proto.Actor server on {addr}");
}
}
}```
Support port 0 in remoting | ```c#
// -----------------------------------------------------------------------
// <copyright file="RemotingSystem.cs" company="Asynkron HB">
// Copyright (C) 2015-2017 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Linq;
using Grpc.Core;
namespace Proto.Remote
{
public static class RemotingSystem
{
private static Server _server;
public static PID EndpointManagerPid { get; private set; }
public static void Start(string host, int port)
{
ProcessRegistry.Instance.RegisterHostResolver(pid => new RemoteProcess(pid));
_server = new Server
{
Services = {Remoting.BindService(new EndpointReader())},
Ports = {new ServerPort(host, port, ServerCredentials.Insecure)}
};
_server.Start();
var boundPort = _server.Ports.Single().BoundPort;
var addr = host + ":" + boundPort;
ProcessRegistry.Instance.Address = addr;
var props = Actor.FromProducer(() => new EndpointManager());
EndpointManagerPid = Actor.Spawn(props);
Console.WriteLine($"[REMOTING] Starting Proto.Actor server on {addr}");
}
}
}``` |
256efbce-364f-4160-a669-5d29278161d1 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GreekNakamaTorrentUpload.WinClass.Helper
{
static class Helper
{
static public void BrowseFiles(TextBox txt_torrent, Label lbl_file)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Torrent files|*.torrent";
ofd.Multiselect = false;
ofd.Title = "Browse the torrent file...";
DialogResult DL = ofd.ShowDialog();
if (DL == DialogResult.OK)
{
txt_torrent.Text = ofd.FileName;
lbl_file.Text = "File Name : " + ofd.SafeFileName;
}
}
}
static public void SaveToJson(string content)
{
string contentForSave = JsonConvert.SerializeObject(content, Formatting.Indented);
File.WriteAllText("settings.json", contentForSave);
}
static public void SaveToJson(string[] contents)
{
string contentForSave = JsonConvert.SerializeObject(contents.ToArray(), Formatting.Indented);
File.WriteAllText("settings.json", contentForSave);
}
static public string LoadFromJson()
{
string loadedContents;
try
{
loadedContents = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText("settings.json"));
}
catch (Exception)
{
return "0x01";
}
return loadedContents;
}
}
}
```
Update the Load & Save Methods with new. | ```c#
using Newtonsoft.Json;
using System;
using System.IO;
using System.Windows.Forms;
namespace GreekNakamaTorrentUpload.WinClass.Helper
{
static class Helper
{
static public Exception LoadedError = new Exception("Error while load the file. Error code: 0x01.");
static public void BrowseFiles(TextBox txt_torrent, Label lbl_file)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Torrent files|*.torrent";
ofd.Multiselect = false;
ofd.Title = "Browse the torrent file...";
DialogResult DL = ofd.ShowDialog();
if (DL == DialogResult.OK)
{
txt_torrent.Text = ofd.FileName;
lbl_file.Text = ofd.SafeFileName;
}
}
}
static public void SaveToJson(string content)
{
string contentForSave = JsonConvert.SerializeObject(content, Formatting.Indented);
File.WriteAllText("settings.json", contentForSave);
}
static public void SaveToJson(Credentials credentials)
{
string contentForSave = JsonConvert.SerializeObject(credentials, Formatting.Indented);
File.WriteAllText("settings.json", contentForSave);
}
static public Credentials LoadFromJson()
{
Credentials loadedContents;
loadedContents = JsonConvert.DeserializeObject<Credentials>(System.IO.File.ReadAllText("settings.json"));
return loadedContents;
}
}
}
``` |
8a421d10-07bb-44ad-a04e-7a6adc7e53bd | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using NUnit.Framework;
using Palaso.TestUtilities;
using Palaso.UI.WindowsForms.WritingSystems;
using Palaso.WritingSystems;
namespace PalasoUIWindowsForms.Tests.WritingSystems
{
[TestFixture]
public class UITests
{
[Test, Ignore("By hand only")]
public void WritingSystemSetupDialog()
{
using (var folder = new TemporaryFolder("WS-Test"))
{
new WritingSystemSetupDialog(folder.Path).ShowDialog();
}
}
[Test, Ignore("By hand only")]
public void WritingSystemSetupViewWithComboAttached()
{
using (var folder = new TemporaryFolder("WS-Test"))
{
var f = new Form();
f.Size=new Size(800,600);
var model = new WritingSystemSetupModel(new LdmlInFolderWritingSystemStore(folder.Path));
var v = new WritingSystemSetupView(model);
var combo = new WSPickerUsingComboBox(model);
f.Controls.Add(combo);
f.Controls.Add(v);
f.ShowDialog();
}
}
}
}```
Add voice option to ui test | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using NUnit.Framework;
using Palaso.TestUtilities;
using Palaso.UI.WindowsForms.WritingSystems;
using Palaso.UI.WindowsForms.WritingSystems.WSTree;
using Palaso.WritingSystems;
namespace PalasoUIWindowsForms.Tests.WritingSystems
{
[TestFixture]
public class UITests
{
[Test, Ignore("By hand only")]
public void WritingSystemSetupDialog()
{
using (var folder = new TemporaryFolder("WS-Test"))
{
var dlg = new WritingSystemSetupDialog(folder.Path);
dlg.WritingSystemSuggestor.SuggestVoice = true;
dlg.ShowDialog();
}
}
[Test, Ignore("By hand only")]
public void WritingSystemSetupViewWithComboAttached()
{
using (var folder = new TemporaryFolder("WS-Test"))
{
var f = new Form();
f.Size=new Size(800,600);
var model = new WritingSystemSetupModel(new LdmlInFolderWritingSystemStore(folder.Path));
var v = new WritingSystemSetupView(model);
var combo = new WSPickerUsingComboBox(model);
f.Controls.Add(combo);
f.Controls.Add(v);
f.ShowDialog();
}
}
}
}``` |
cfc5d432-963f-4d3d-9b47-c6fa2549e8a3 | {
"language": "C#"
} | ```c#
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
namespace Lokad.Cqrs.Core.Inbox.Events
{
public sealed class FailedToAccessStorage : ISystemEvent
{
public Exception Exception { get; private set; }
public string QueueName { get; private set; }
public string MessageId { get; private set; }
public FailedToAccessStorage(Exception exception, string queueName, string messageId)
{
Exception = exception;
QueueName = queueName;
MessageId = messageId;
}
}
}```
Access storage failure is readable. | ```c#
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
namespace Lokad.Cqrs.Core.Inbox.Events
{
public sealed class FailedToAccessStorage : ISystemEvent
{
public Exception Exception { get; private set; }
public string QueueName { get; private set; }
public string MessageId { get; private set; }
public FailedToAccessStorage(Exception exception, string queueName, string messageId)
{
Exception = exception;
QueueName = queueName;
MessageId = messageId;
}
public override string ToString()
{
return string.Format("Failed to read '{0}' from '{1}': {2}", MessageId, QueueName, Exception.Message);
}
}
}``` |
8582aecc-24d1-47e0-8465-0eb482f3efb2 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Codestellation.Galaxy.Domain;
using Codestellation.Quarks.Collections;
using Nejdb.Bson;
namespace Codestellation.Galaxy.WebEnd.Models
{
public class DeploymentListModel
{
public readonly DeploymentModel[] Deployments;
public readonly KeyValuePair<ObjectId, string>[] AllFeeds;
public DeploymentListModel(DashBoard dashBoard)
{
AllFeeds = dashBoard.Feeds.ConvertToArray(feed => new KeyValuePair<ObjectId, string>(feed.Id, feed.Name), dashBoard.Feeds.Count);
Deployments = dashBoard.Deployments.ConvertToArray(x => new DeploymentModel(x, AllFeeds), dashBoard.Deployments.Count);
Groups = Deployments.Select(GetGroup).Distinct().ToArray();
}
public string[] Groups { get; set; }
public int Count
{
get { return Deployments.Length; }
}
public IEnumerable<DeploymentModel> GetModelsByGroup(string serviceGroup)
{
var modelsByGroup = Deployments
.Where(model => serviceGroup.Equals(GetGroup(model), StringComparison.Ordinal))
.OrderBy(x => x.ServiceFullName);
return modelsByGroup;
}
private static string GetGroup(DeploymentModel model)
{
return string.IsNullOrWhiteSpace(model.Group) ? "Everything Else" : model.Group;
}
}
}```
Sort deployment groups in deployment list | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Codestellation.Galaxy.Domain;
using Codestellation.Quarks.Collections;
using Nejdb.Bson;
namespace Codestellation.Galaxy.WebEnd.Models
{
public class DeploymentListModel
{
public readonly DeploymentModel[] Deployments;
public readonly KeyValuePair<ObjectId, string>[] AllFeeds;
public DeploymentListModel(DashBoard dashBoard)
{
AllFeeds = dashBoard.Feeds.ConvertToArray(feed => new KeyValuePair<ObjectId, string>(feed.Id, feed.Name), dashBoard.Feeds.Count);
Deployments = dashBoard.Deployments.ConvertToArray(x => new DeploymentModel(x, AllFeeds), dashBoard.Deployments.Count);
Groups = Deployments.Select(GetGroup).Distinct().OrderBy(x => x).ToArray();
}
public string[] Groups { get; set; }
public int Count
{
get { return Deployments.Length; }
}
public IEnumerable<DeploymentModel> GetModelsByGroup(string serviceGroup)
{
var modelsByGroup = Deployments
.Where(model => serviceGroup.Equals(GetGroup(model), StringComparison.Ordinal))
.OrderBy(x => x.ServiceFullName);
return modelsByGroup;
}
private static string GetGroup(DeploymentModel model)
{
return string.IsNullOrWhiteSpace(model.Group) ? "Everything Else" : model.Group;
}
}
}``` |
ca8a5258-7f14-45fa-b1c9-145f978d1a26 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace ApiTest.InventoryApi
{
public class UnitOfMeasure
{
public int id { get; set; }
public string code { get; set; }
}
public sealed class InventoryStatus
{
public static string Active = "active";
public static string OnHold = "onhold";
public static string Inactive = "inactive";
}
public sealed class InventoryType
{
public static string Normal = "normal";
public static string NonPhysical = "nonPhysical";
public static string Manufactured = "manufactured";
public static string Kitted = "kitted";
public static string RawMaterial = "rawMaterial";
}
public class Inventory
{
public int id { get; set; }
public string partNo { get; set; }
public string whse { get; set; }
public string description { get; set; }
public string type { get; set; }
public string status { get; set; }
public decimal onHandQty { get; set; }
public decimal committedQty { get; set; }
public decimal backorderQty { get; set; }
public Dictionary<string, UnitOfMeasure> unitOfMeasures { get; set; }
}
public class InventoryClient : BaseObjectClient<Inventory>
{
public InventoryClient(ApiClient client) : base(client) { }
public override string Resource
{
get
{
return "inventory/items/";
}
}
}
}```
Update inventory type and status mappings | ```c#
using System.Collections.Generic;
namespace ApiTest.InventoryApi
{
public class UnitOfMeasure
{
public int id { get; set; }
public string code { get; set; }
}
public sealed class InventoryStatus
{
public static string Active = 0;
public static string OnHold = 1;
public static string Inactive = 2;
}
public sealed class InventoryType
{
public static string Normal = "N";
public static string NonPhysical = "V";
public static string Manufactured = "M";
public static string Kitted = "K";
public static string RawMaterial = "R";
}
public class Inventory
{
public int id { get; set; }
public string partNo { get; set; }
public string whse { get; set; }
public string description { get; set; }
public string type { get; set; }
public string status { get; set; }
public decimal onHandQty { get; set; }
public decimal committedQty { get; set; }
public decimal backorderQty { get; set; }
public Dictionary<string, UnitOfMeasure> unitOfMeasures { get; set; }
}
public class InventoryClient : BaseObjectClient<Inventory>
{
public InventoryClient(ApiClient client) : base(client) { }
public override string Resource
{
get
{
return "inventory/items/";
}
}
}
}
``` |
be6273a5-e240-4a55-bc6a-34638e73725f | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
using Realms;
using System.Threading;
namespace IntegrationTests.Shared
{
[TestFixture]
public class NotificationTests
{
private string _databasePath;
private Realm _realm;
private void WriteOnDifferentThread(Action<Realm> action)
{
var thread = new Thread(() =>
{
var r = Realm.GetInstance(_databasePath);
r.Write(() => action(r));
r.Close();
});
thread.Start();
thread.Join();
}
[Test]
public void SimpleTest()
{
// Arrange
// Act
}
}
}
```
Add the simples notification test | ```c#
using System;
using NUnit.Framework;
using Realms;
using System.Threading;
using System.IO;
namespace IntegrationTests.Shared
{
[TestFixture]
public class NotificationTests
{
private string _databasePath;
private Realm _realm;
private void WriteOnDifferentThread(Action<Realm> action)
{
var thread = new Thread(() =>
{
var r = Realm.GetInstance(_databasePath);
r.Write(() => action(r));
r.Close();
});
thread.Start();
thread.Join();
}
[SetUp]
private void Setup()
{
_databasePath = Path.GetTempFileName();
_realm = Realm.GetInstance(_databasePath);
}
[Test]
public void ShouldTriggerRealmChangedEvent()
{
// Arrange
var wasNotified = false;
_realm.RealmChanged += (sender, e) => { wasNotified = true; };
// Act
WriteOnDifferentThread((realm) =>
{
realm.CreateObject<Person>();
});
// Assert
Assert.That(wasNotified, "RealmChanged notification was not triggered");
}
}
}
``` |
328df318-927a-4f0a-a363-6138a5f1b44a | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SO115App.FakePersistenceJSon.GestioneIntervento
{
public class GetMaxCodice : IGetMaxCodice
{
public int GetMax()
{
int MaxIdSintesi;
string filepath = "Fake/ListaRichiesteAssistenza.json";
string json;
using (StreamReader r = new StreamReader(filepath))
{
json = r.ReadToEnd();
}
List<RichiestaAssistenzaRead> ListaRichieste = JsonConvert.DeserializeObject<List<RichiestaAssistenzaRead>>(json);
if (ListaRichieste != null)
MaxIdSintesi = Convert.ToInt16(ListaRichieste.OrderByDescending(x => x.Codice).FirstOrDefault().Codice.Split('-')[1]);
else
MaxIdSintesi = 1;
return MaxIdSintesi;
}
}
}
```
Fix - Corretto reperimento codice chiamata | ```c#
using Newtonsoft.Json;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SO115App.FakePersistenceJSon.GestioneIntervento
{
public class GetMaxCodice : IGetMaxCodice
{
public int GetMax()
{
int MaxIdSintesi;
string filepath = "Fake/ListaRichiesteAssistenza.json";
string json;
using (StreamReader r = new StreamReader(filepath))
{
json = r.ReadToEnd();
}
List<RichiestaAssistenzaRead> ListaRichieste = JsonConvert.DeserializeObject<List<RichiestaAssistenzaRead>>(json);
if (ListaRichieste != null)
MaxIdSintesi = Convert.ToInt16(ListaRichieste.OrderByDescending(x => x.Codice).FirstOrDefault().Codice.Split('-')[1]);
else
MaxIdSintesi = 0;
return MaxIdSintesi;
}
}
}
``` |
6ffc30f8-cc1f-40f8-837a-9d29a62a1b08 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GGProductions.LetterStorm.Data.Collections;
namespace Test.GGProductions.LetterStorm.Data.Collections
{
[TestClass]
public class LessonBookTests
{
[TestMethod]
public void CreateSampleLessonTest()
{
// Create a lesson book with a sample lesson
LessonBook lessonBook = new LessonBook();
lessonBook.CreateSampleLesson();
// Verify a lesson was created and that it has the correct name
Assert.AreEqual(1, lessonBook.Lessons.Count);
Assert.AreEqual("Sample Lesson", lessonBook.Lessons[0].Name);
// Verify the lesson's words were created
Assert.AreEqual(4, lessonBook.Lessons[0].Words.Count);
Assert.AreEqual("cat", lessonBook.Lessons[0].Words[0].Text);
Assert.AreEqual("dog", lessonBook.Lessons[0].Words[1].Text);
Assert.AreEqual("fish", lessonBook.Lessons[0].Words[2].Text);
Assert.AreEqual("horse", lessonBook.Lessons[0].Words[3].Text);
}
}
}
```
Update text case for CreateSampleLesson | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GGProductions.LetterStorm.Data.Collections;
namespace Test.GGProductions.LetterStorm.Data.Collections
{
[TestClass]
public class LessonBookTests
{
[TestMethod]
public void CreateSampleLessonTest()
{
// Create a lesson book with a sample lesson
LessonBook lessonBook = new LessonBook();
lessonBook.CreateSampleLessons();
// Verify a lesson was created and that it has the correct name
Assert.AreEqual(5, lessonBook.Lessons.Count);
Assert.AreEqual("K5 Sample", lessonBook.Lessons[0].Name);
// Verify the lesson's words were created
Assert.AreEqual(5, lessonBook.Lessons[0].Words.Count);
Assert.AreEqual("cat", lessonBook.Lessons[0].Words[0].Text);
Assert.AreEqual("dog", lessonBook.Lessons[0].Words[1].Text);
Assert.AreEqual("bug", lessonBook.Lessons[0].Words[2].Text);
Assert.AreEqual("fish", lessonBook.Lessons[0].Words[3].Text);
Assert.AreEqual("horse", lessonBook.Lessons[0].Words[4].Text);
}
}
}
``` |
1074fc0b-ab00-433f-bc1d-d7e9050c7d0d | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.Note
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Width = 160;
Height = 200;
}
[DisplayName("Saved Text")]
public string Text { get; set; }
}
}```
Change "Note" widget default height | ```c#
using System.ComponentModel;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.Note
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Width = 160;
Height = 132;
}
[DisplayName("Saved Text")]
public string Text { get; set; }
}
}``` |
b58952cd-4457-4240-855d-8975bd5096c9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KataPotter
{
public class KataPotterPriceCalculator
{
private static readonly double BOOK_UNIT_PRICE = 8;
public double Calculate(Dictionary<string, int> booksToBuy)
{
var totalCount = booksToBuy.Sum(i => i.Value);
var totalPrice = totalCount * BOOK_UNIT_PRICE;
return totalPrice;
}
}
}
```
Add two book discount scenario | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KataPotter
{
public class KataPotterPriceCalculator
{
private static readonly double BOOK_UNIT_PRICE = 8;
private static readonly double TWO_BOOKS_DISCOUNT_RATE = 0.95;
public double Calculate(Dictionary<string, int> booksToBuy)
{
var totalCount = booksToBuy.Sum(i => i.Value);
var totalPrice = totalCount * BOOK_UNIT_PRICE;
if (totalCount > 1)
{
totalPrice = totalPrice * TWO_BOOKS_DISCOUNT_RATE;
}
return totalPrice;
}
}
}
``` |
eef61457-6717-46f7-af4d-b4f72d89e1d4 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.DeleteRuoliUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti.GestioneRuoli;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneRuoli
{
public class NotificationDeleteRuolo : INotifyDeleteRuolo
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteRuolo(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteRuoliUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", utente.Id).ConfigureAwait(false);
await _notificationHubContext.Clients.All.SendAsync("NotifyModificatoRuoloUtente", utente.Id).ConfigureAwait(false);
}
}
}
```
Fix - Corretta notifica delete utente | ```c#
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.DeleteRuoliUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti.GestioneRuoli;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneRuoli
{
public class NotificationDeleteRuolo : INotifyDeleteRuolo
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteRuolo(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteRuoliUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
//await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", utente.Id).ConfigureAwait(false);
await _notificationHubContext.Clients.All.SendAsync("NotifyModificatoRuoloUtente", utente.Id).ConfigureAwait(false);
}
}
}
``` |
c61b2d8f-9de7-48f0-ab6c-2db0d8ba7a2e | {
"language": "C#"
} | ```c#
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Oogstplanner.Models;
using Oogstplanner.Data;
using Oogstplanner.Services;
namespace Oogstplanner.Web
{
public static class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<OogstplannerUnitOfWork>()
.As<IOogstplannerUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterType<OogstplannerContext>()
.As<IOogstplannerContext>()
.InstancePerRequest();
var repositoryInstances = new RepositoryFactories();
builder.RegisterInstance(repositoryInstances)
.As<RepositoryFactories>()
.SingleInstance();
builder.RegisterType<RepositoryProvider>()
.As<IRepositoryProvider>()
.InstancePerRequest();
builder.RegisterAssemblyTypes(typeof(ServiceBase).Assembly)
.AsImplementedInterfaces()
.Except<UserService>()
.Except<AnonymousUserService>();
builder.RegisterType<AnonymousUserService>()
.Keyed<IUserService>(AuthenticatedStatus.Anonymous);
builder.RegisterType<UserService>()
.Keyed<IUserService>(AuthenticatedStatus.Authenticated);
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
```
Set lifetime scope of services to instance per request | ```c#
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Oogstplanner.Models;
using Oogstplanner.Data;
using Oogstplanner.Services;
namespace Oogstplanner.Web
{
public static class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<OogstplannerUnitOfWork>()
.As<IOogstplannerUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterType<OogstplannerContext>()
.As<IOogstplannerContext>()
.InstancePerRequest();
var repositoryFactories = new RepositoryFactories();
builder.RegisterInstance(repositoryFactories)
.As<RepositoryFactories>()
.SingleInstance();
builder.RegisterType<RepositoryProvider>()
.As<IRepositoryProvider>()
.InstancePerRequest();
builder.RegisterAssemblyTypes(typeof(ServiceBase).Assembly)
.AsImplementedInterfaces()
.Except<UserService>()
.Except<AnonymousUserService>()
.InstancePerRequest();
builder.RegisterType<AnonymousUserService>()
.Keyed<IUserService>(AuthenticatedStatus.Anonymous)
.InstancePerRequest();
builder.RegisterType<UserService>()
.Keyed<IUserService>(AuthenticatedStatus.Authenticated)
.InstancePerRequest();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
``` |
5c2c8d11-462d-4cde-9a85-2c90d2d4259c | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
[ContentType(ContentTypeNames.XamlContentType)]
[DisableUserExperience(disableUserExperience: true)] // Remove this when we are ready to use LSP everywhere
[Export(typeof(ILanguageClient))]
internal class XamlLanguageServerClient : AbstractLanguageServerClient
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, true)]
public XamlLanguageServerClient(XamlLanguageServerProtocol languageServerProtocol, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspSolutionProvider solutionProvider)
: base(languageServerProtocol, workspace, diagnosticService, listenerProvider, solutionProvider, diagnosticsClientName: null)
{
}
/// <summary>
/// Gets the name of the language client (displayed to the user).
/// </summary>
public override string Name => Resources.Xaml_Language_Server_Client;
}
}
```
Remove unnecessary fields/methods for lsp push diagnostics | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
[ContentType(ContentTypeNames.XamlContentType)]
[DisableUserExperience(disableUserExperience: true)] // Remove this when we are ready to use LSP everywhere
[Export(typeof(ILanguageClient))]
internal class XamlLanguageServerClient : AbstractLanguageServerClient
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, true)]
public XamlLanguageServerClient(XamlLanguageServerProtocol languageServerProtocol, VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, ILspSolutionProvider solutionProvider)
: base(languageServerProtocol, workspace, listenerProvider, solutionProvider, diagnosticsClientName: null)
{
}
/// <summary>
/// Gets the name of the language client (displayed to the user).
/// </summary>
public override string Name => Resources.Xaml_Language_Server_Client;
}
}
``` |
a70539f6-9d37-45b9-91d9-b1c8e026a8aa | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.Threading;
namespace StreamDeckSharp.Internals
{
internal class Throttle
{
private readonly Stopwatch stopwatch = Stopwatch.StartNew();
private long sumBytesInWindow = 0;
public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity;
public void MeasureAndBlock(int bytes)
{
sumBytesInWindow += bytes;
var elapsedSeconds = stopwatch.Elapsed.TotalSeconds;
var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit;
if (elapsedSeconds < estimatedSeconds)
{
var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000));
Thread.Sleep(delta);
}
if (elapsedSeconds >= 1)
{
stopwatch.Restart();
sumBytesInWindow = 0;
}
}
}
}
```
Debug output on throttled throughput | ```c#
using System;
using System.Diagnostics;
using System.Threading;
namespace StreamDeckSharp.Internals
{
internal class Throttle
{
private readonly Stopwatch stopwatch = Stopwatch.StartNew();
private long sumBytesInWindow = 0;
private int sleepCount = 0;
public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity;
public void MeasureAndBlock(int bytes)
{
sumBytesInWindow += bytes;
var elapsedSeconds = stopwatch.Elapsed.TotalSeconds;
var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit;
if (elapsedSeconds < estimatedSeconds)
{
var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000));
Thread.Sleep(delta);
sleepCount++;
}
if (elapsedSeconds >= 1)
{
if (sleepCount > 1)
{
Debug.WriteLine($"[Throttle] {sumBytesInWindow / elapsedSeconds}");
}
stopwatch.Restart();
sumBytesInWindow = 0;
sleepCount = 0;
}
}
}
}
``` |
57cae0c8-3fa3-4c24-9ca0-460dce5ec6bb | {
"language": "C#"
} | ```c#
using System;
using Symbooglix.Solver;
namespace Symbooglix
{
namespace Solver
{
public class CVC4SMTLIBSolver : SimpleSMTLIBSolver
{
SMTLIBQueryPrinter.Logic LogicToUse = SMTLIBQueryPrinter.Logic.ALL_SUPPORTED; // Non standard
public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess) :
base(useNamedAttributes, pathToSolver, "--lang smt2 --incremental", persistentProcess) // CVC4 specific command line flags
{
}
// HACK:
public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess, SMTLIBQueryPrinter.Logic logic) :
this(useNamedAttributes, pathToSolver, persistentProcess)
{
LogicToUse = logic;
}
protected override void SetSolverOptions()
{
Printer.PrintSetLogic(LogicToUse);
}
}
}
}
```
Fix CVC4 support (requires a new version that supports the reset command). | ```c#
using System;
using Symbooglix.Solver;
namespace Symbooglix
{
namespace Solver
{
public class CVC4SMTLIBSolver : SimpleSMTLIBSolver
{
SMTLIBQueryPrinter.Logic LogicToUse = SMTLIBQueryPrinter.Logic.ALL_SUPPORTED; // Non standard
public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess) :
base(useNamedAttributes, pathToSolver, "--lang smt2 --incremental", persistentProcess) // CVC4 specific command line flags
{
}
// HACK:
public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess, SMTLIBQueryPrinter.Logic logic) :
this(useNamedAttributes, pathToSolver, persistentProcess)
{
// We should not use DO_NOT_SET because CVC4 complains if no
// logic is set which causes a SolverErrorException to be raised.
if (logic != SMTLIBQueryPrinter.Logic.DO_NOT_SET)
LogicToUse = logic;
}
protected override void SetSolverOptions()
{
Printer.PrintSetLogic(LogicToUse);
}
}
}
}
``` |
425ed006-74a9-4d33-a7a4-5fc8a1feba3f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Cipher {
class Utility {
public static string directory = @"c:\code\cypher_files";
/// <summary>
/// Allows user to choose to display the password on the screen as is being typed.
/// </summary>
/// <param name="displayPassword">
/// Indicates whether or not password displays on the screen.
/// </param>
/// <returns>
/// A password string.
/// </returns>
public static string GetPassword(string displayPassword) {
string password = "";
if (displayPassword == "y" || displayPassword == "") {
password = Console.ReadLine();
}
if (displayPassword == "n") {
while (true) {
var pressedKey = System.Console.ReadKey(true);
// Get all typed keys until 'Enter' is pressed.
if (pressedKey.Key == ConsoleKey.Enter) {
Console.WriteLine("");
break;
}
password += pressedKey.KeyChar;
}
}
return password;
}
public static void SaveFileToDisk(string fileName, byte[] fileContents) {
File.WriteAllBytes(fileName, fileContents);
}
}
}
```
Remove unused code and updated directory location. | ```c#
using System;
using System.IO;
namespace Cipher {
class Utility {
public static string directory = "/Users/emiranda/Documents/code/c#/cipher_files/";
/// <summary>
/// Allows user to choose to display the password on the screen as is being typed.
/// </summary>
/// <param name="displayPassword">
/// Indicates whether or not password displays on the screen.
/// </param>
/// <returns>
/// A password string.
/// </returns>
public static string GetPassword(string displayPassword) {
string password = "";
if (displayPassword == "y" || displayPassword == "") {
password = Console.ReadLine();
}
if (displayPassword == "n") {
while (true) {
var pressedKey = System.Console.ReadKey(true);
// Get all typed keys until 'Enter' is pressed.
if (pressedKey.Key == ConsoleKey.Enter) {
Console.WriteLine("");
break;
}
password += pressedKey.KeyChar;
}
}
return password;
}
public static void SaveFileToDisk(string fileName, byte[] fileContents) {
File.WriteAllBytes(fileName, fileContents);
}
}
}
``` |
262f854a-5468-4553-9127-d904d2e8e31f | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Security.Claims;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Authentication
{
/// <summary>
/// Used by the <see cref="IAuthenticationService"/> for claims transformation.
/// </summary>
public interface IClaimsTransformation
{
/// <summary>
/// Provides a central transformation point to change the specified principal.
/// </summary>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> to transform.</param>
/// <returns>The transformed principal.</returns>
Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal);
}
}```
Add comment for claims transform | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Security.Claims;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Authentication
{
/// <summary>
/// Used by the <see cref="IAuthenticationService"/> for claims transformation.
/// </summary>
public interface IClaimsTransformation
{
/// <summary>
/// Provides a central transformation point to change the specified principal.
/// Note: this will be run on each AuthenticateAsync call, so its safer to
/// return a new ClaimsPrincipal if your transformation is not idempotent.
/// </summary>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> to transform.</param>
/// <returns>The transformed principal.</returns>
Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal);
}
}``` |
5c0d9850-050e-4bb5-a3ec-6b5216373fe5 | {
"language": "C#"
} | ```c#
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using Semver;
using Umbraco.Core.Models;
namespace Umbraco.Core.Persistence.Repositories.Implement
{
internal class UpgradeCheckRepository : IUpgradeCheckRepository
{
private static HttpClient _httpClient;
private const string RestApiUpgradeChecklUrl = "https://our.umbraco.com/umbraco/api/UpgradeCheck/CheckUpgrade";
public async Task<UpgradeResult> CheckUpgradeAsync(SemVersion version)
{
try
{
if (_httpClient == null)
_httpClient = new HttpClient();
var task = await _httpClient.PostAsync(RestApiUpgradeChecklUrl, new CheckUpgradeDto(version), new JsonMediaTypeFormatter());
var result = await task.Content.ReadAsAsync<UpgradeResult>();
return result ?? new UpgradeResult("None", "", "");
}
catch (HttpRequestException)
{
// this occurs if the server for Our is down or cannot be reached
return new UpgradeResult("None", "", "");
}
}
private class CheckUpgradeDto
{
public CheckUpgradeDto(SemVersion version)
{
VersionMajor = version.Major;
VersionMinor = version.Minor;
VersionPatch = version.Patch;
VersionComment = version.Prerelease;
}
public int VersionMajor { get; }
public int VersionMinor { get; }
public int VersionPatch { get; }
public string VersionComment { get; }
}
}
}
```
Handle Invalid format for Upgrade check | ```c#
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using Semver;
using Umbraco.Core.Models;
namespace Umbraco.Core.Persistence.Repositories.Implement
{
internal class UpgradeCheckRepository : IUpgradeCheckRepository
{
private static HttpClient _httpClient;
private const string RestApiUpgradeChecklUrl = "https://our.umbraco.com/umbraco/api/UpgradeCheck/CheckUpgrade";
public async Task<UpgradeResult> CheckUpgradeAsync(SemVersion version)
{
try
{
if (_httpClient == null)
_httpClient = new HttpClient();
var task = await _httpClient.PostAsync(RestApiUpgradeChecklUrl, new CheckUpgradeDto(version), new JsonMediaTypeFormatter());
var result = await task.Content.ReadAsAsync<UpgradeResult>();
return result ?? new UpgradeResult("None", "", "");
}
catch (UnsupportedMediaTypeException)
{
// this occurs if the server for Our is up but doesn't return a valid result (ex. content type)
return new UpgradeResult("None", "", "");
}
catch (HttpRequestException)
{
// this occurs if the server for Our is down or cannot be reached
return new UpgradeResult("None", "", "");
}
}
private class CheckUpgradeDto
{
public CheckUpgradeDto(SemVersion version)
{
VersionMajor = version.Major;
VersionMinor = version.Minor;
VersionPatch = version.Patch;
VersionComment = version.Prerelease;
}
public int VersionMajor { get; }
public int VersionMinor { get; }
public int VersionPatch { get; }
public string VersionComment { get; }
}
}
}
``` |
8a777091-f319-4c56-a801-3c6e56fc604b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Hello_MultiScreen_iPhone
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
//---- declarations
UIWindow window;
UINavigationController rootNavigationController;
// This method is invoked when the application has loaded its UI and it is ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
this.window = new UIWindow (UIScreen.MainScreen.Bounds);
//---- instantiate a new navigation controller
this.rootNavigationController = new UINavigationController();
//---- instantiate a new home screen
HomeScreen homeScreen = new HomeScreen();
//---- add the home screen to the navigation controller (it'll be the top most screen)
this.rootNavigationController.PushViewController(homeScreen, false);
//---- set the root view controller on the window. the nav controller will handle the rest
this.window.RootViewController = this.rootNavigationController;
this.window.MakeKeyAndVisible ();
return true;
}
}
}
```
Remove class variable declaration for UINavigationController | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Hello_MultiScreen_iPhone
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
//---- declarations
UIWindow window;
// This method is invoked when the application has loaded its UI and it is ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
this.window = new UIWindow (UIScreen.MainScreen.Bounds);
//---- instantiate a new navigation controller
var rootNavigationController = new UINavigationController();
//---- instantiate a new home screen
HomeScreen homeScreen = new HomeScreen();
//---- add the home screen to the navigation controller (it'll be the top most screen)
rootNavigationController.PushViewController(homeScreen, false);
//---- set the root view controller on the window. the nav controller will handle the rest
this.window.RootViewController = rootNavigationController;
this.window.MakeKeyAndVisible ();
return true;
}
}
}
``` |
cd7a5939-57e8-4893-8f4e-a9b538b39147 | {
"language": "C#"
} | ```c#
using LogicalShift.Reason.Api;
using LogicalShift.Reason.Unification;
using System;
using System.Collections.Generic;
namespace LogicalShift.Reason
{
/// <summary>
/// Helper methods for performing unification
/// </summary>
public static class BasicUnification
{
/// <summary>
/// Returns the possible ways that a query term can unify with a program term
/// </summary>
public static IEnumerable<ILiteral> Unify(this ILiteral query, ILiteral program)
{
var simpleUnifier = new SimpleUnifier();
var traceUnifier = new TraceUnifier(simpleUnifier);
// Run the unifier
try
{
Console.WriteLine(query);
traceUnifier.QueryUnifier.Compile(query);
simpleUnifier.PrepareToRunProgram();
Console.WriteLine(program);
traceUnifier.ProgramUnifier.Compile(program);
}
catch (InvalidOperationException)
{
// No results
// TODO: really should report failure in a better way
yield break;
}
// Retrieve the unified value for the program
// TODO: eventually we'll need to use a unification key
var result = simpleUnifier.UnifiedValue(program.UnificationKey ?? program);
// If the result was valid, return as the one value from this function
if (result != null)
{
yield return result;
}
}
}
}
```
Remove tracing from the unifier | ```c#
using LogicalShift.Reason.Api;
using LogicalShift.Reason.Unification;
using System;
using System.Collections.Generic;
namespace LogicalShift.Reason
{
/// <summary>
/// Helper methods for performing unification
/// </summary>
public static class BasicUnification
{
/// <summary>
/// Returns the possible ways that a query term can unify with a program term
/// </summary>
public static IEnumerable<ILiteral> Unify(this ILiteral query, ILiteral program)
{
var simpleUnifier = new SimpleUnifier();
// Run the unifier
try
{
simpleUnifier.QueryUnifier.Compile(query);
simpleUnifier.PrepareToRunProgram();
simpleUnifier.ProgramUnifier.Compile(program);
}
catch (InvalidOperationException)
{
// No results
// TODO: really should report failure in a better way
yield break;
}
// Retrieve the unified value for the program
var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query);
// If the result was valid, return as the one value from this function
if (result != null)
{
yield return result;
}
}
}
}
``` |
60c0963c-58ff-45fb-97e1-f6e0f2e37294 | {
"language": "C#"
} | ```c#
using RGiesecke.DllExport;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using TGS.Interface;
using TGS.Interface.Components;
namespace TGS.Interface.Bridge
{
/// <summary>
/// Holds the proc that DD calls to access <see cref="ITGInterop"/>
/// </summary>
public static class DreamDaemonBridge
{
/// <summary>
/// The proc that DD calls to access <see cref="ITGInterop"/>
/// </summary>
/// <param name="argc">The number of arguments passed</param>
/// <param name="args">The arguments passed</param>
/// <returns>0</returns>
[DllExport("DDEntryPoint", CallingConvention = CallingConvention.Cdecl)]
public static int DDEntryPoint(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 0)]string[] args)
{
try
{
var parsedArgs = new List<string>();
parsedArgs.AddRange(args);
var instance = parsedArgs[0];
parsedArgs.RemoveAt(0);
using (var I = new ServerInterface())
if(I.ConnectToInstance(instance, true).HasFlag(ConnectivityLevel.Connected))
I.GetComponent<ITGInterop>().InteropMessage(String.Join(" ", parsedArgs));
}
catch { }
return 0;
}
}
}
```
Update bridge to use new interface | ```c#
using RGiesecke.DllExport;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace TGS.Interface.Bridge
{
/// <summary>
/// Holds the proc that DD calls to access <see cref="ITGInterop"/>
/// </summary>
public static class DreamDaemonBridge
{
/// <summary>
/// The proc that DD calls to access <see cref="ITGInterop"/>
/// </summary>
/// <param name="argc">The number of arguments passed</param>
/// <param name="args">The arguments passed</param>
/// <returns>0</returns>
[DllExport("DDEntryPoint", CallingConvention = CallingConvention.Cdecl)]
public static int DDEntryPoint(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 0)]string[] args)
{
try
{
var parsedArgs = new List<string>();
parsedArgs.AddRange(args);
var instance = parsedArgs[0];
parsedArgs.RemoveAt(0);
using (var I = new ServerInterface())
I.Server.GetInstance(instance).Interop.InteropMessage(String.Join(" ", parsedArgs));
}
catch { }
return 0;
}
}
}
``` |
7ca50778-f8f0-405a-821e-a8b82506591e | {
"language": "C#"
} | ```c#
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using OdeToFood.Entities;
using OdeToFood.Services;
using OdeToFood.ViewModels;
namespace OdeToFood.Controllers
{
public class HomeController : Controller
{
private IRestaurantData _restaurantData;
private IGreeter _greeter;
public HomeController(IRestaurantData restaurantData, IGreeter greeter)
{
_restaurantData = restaurantData;
_greeter = greeter;
}
public IActionResult Index()
{
var model = new HomePageViewModel()
{
Message = _greeter.GetGreeting(),
Restaurants = _restaurantData.GetAll()
};
return View(model);
}
public IActionResult Details(int id)
{
var model = _restaurantData.Get(id);
if (model == null)
{
return RedirectToAction(nameof(Index));
}
return View(model);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(RestaurantEditViewModel model)
{
var restaurant = new Restaurant()
{
Name = model.Name,
Cuisine = model.Cuisine
};
restaurant = _restaurantData.Add(restaurant);
return View(nameof(Details), restaurant);
}
}
}
```
Add POST REDIRECT GET Pattern to controller | ```c#
using Microsoft.AspNetCore.Mvc;
using OdeToFood.Entities;
using OdeToFood.Services;
using OdeToFood.ViewModels;
namespace OdeToFood.Controllers
{
public class HomeController : Controller
{
private IRestaurantData _restaurantData;
private IGreeter _greeter;
public HomeController(IRestaurantData restaurantData, IGreeter greeter)
{
_restaurantData = restaurantData;
_greeter = greeter;
}
public IActionResult Index()
{
var model = new HomePageViewModel()
{
Message = _greeter.GetGreeting(),
Restaurants = _restaurantData.GetAll()
};
return View(model);
}
public IActionResult Details(int id)
{
var model = _restaurantData.Get(id);
if (model == null)
{
return RedirectToAction(nameof(Index));
}
return View(model);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(RestaurantEditViewModel model)
{
var restaurant = new Restaurant()
{
Name = model.Name,
Cuisine = model.Cuisine
};
restaurant = _restaurantData.Add(restaurant);
return RedirectToAction(nameof(Details), new { Id = restaurant.Id });
}
}
}
``` |
7c311dc6-7c58-46de-8b0b-7e17cdd57671 | {
"language": "C#"
} | ```c#
#region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Runtime.CompilerServices;
namespace NodaTime.Calendars
{
/// <summary>
/// <para>
/// The NodaTime.Calendar namespace contains types related to calendars beyond the
/// <see cref="CalendarSystem"/> type in the core NodaTime namespace.
/// </para>
/// </summary>
[CompilerGenerated]
internal class NamespaceDoc
{
// No actual code here - it's just for the sake of documenting the namespace.
}
}
```
Fix a typo in the NodaTime.Calendars namespace summary. | ```c#
#region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Runtime.CompilerServices;
namespace NodaTime.Calendars
{
/// <summary>
/// <para>
/// The NodaTime.Calendars namespace contains types related to calendars beyond the
/// <see cref="CalendarSystem"/> type in the core NodaTime namespace.
/// </para>
/// </summary>
[CompilerGenerated]
internal class NamespaceDoc
{
// No actual code here - it's just for the sake of documenting the namespace.
}
}
``` |
d71a4119-2453-4659-9294-19910e0d1111 | {
"language": "C#"
} | ```c#
var configuration = Argument("configuration", "Debug");
Task("Clean")
.Does(() =>
{
CleanDirectory("./artifacts/");
});
Task("Restore")
.Does(() =>
{
DotNetCoreRestore();
});
Task("Build")
.Does(() =>
{
DotNetCoreBuild("./src/**/project.json", new DotNetCoreBuildSettings
{
Configuration = configuration
});
});
Task("Pack")
.Does(() =>
{
new List<string>
{
"Stormpath.Owin.Abstractions",
"Stormpath.Owin.Middleware",
"Stormpath.Owin.Views.Precompiled"
}.ForEach(name =>
{
DotNetCorePack("./src/" + name + "/project.json", new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = "./artifacts/"
});
});
});
Task("Test")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.Does(() =>
{
new List<string>
{
"Stormpath.Owin.UnitTest"
}.ForEach(name =>
{
DotNetCoreTest("./test/" + name + "/project.json");
});
});
Task("Default")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("Pack");
var target = Argument("target", "Default");
RunTarget(target);```
Update cake script to csproj | ```c#
var configuration = Argument("configuration", "Debug");
Task("Clean")
.Does(() =>
{
CleanDirectory("./artifacts/");
});
Task("Restore")
.Does(() =>
{
DotNetCoreRestore();
});
Task("Build")
.Does(() =>
{
DotNetCoreBuild("./src/**/*.csproj", new DotNetCoreBuildSettings
{
Configuration = configuration
});
});
Task("Pack")
.Does(() =>
{
new List<string>
{
"Stormpath.Owin.Abstractions",
"Stormpath.Owin.Middleware",
"Stormpath.Owin.Views.Precompiled"
}.ForEach(name =>
{
DotNetCorePack("./src/" + name + ".csproj", new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = "./artifacts/"
});
});
});
Task("Test")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.Does(() =>
{
new List<string>
{
"Stormpath.Owin.UnitTest"
}.ForEach(name =>
{
DotNetCoreTest("./test/" + name + ".csproj");
});
});
Task("Default")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("Pack");
var target = Argument("target", "Default");
RunTarget(target);``` |
d202cf96-d467-463c-8248-84ea8163fbcb | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyProduct("NuGet Package Explorer")]
[assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")]
[assembly: AssemblyTitle("NuGetPackageExplorer.Types")]
[assembly: AssemblyDescription("Contains types to enable the plugin architecture in NuGet Package Explorer.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8bdc7953-73c3-47d6-b0c5-41fda3d55e42")]```
Update assembly version of Types.dll to 3.7 | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyProduct("NuGet Package Explorer")]
[assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")]
[assembly: AssemblyTitle("NuGetPackageExplorer.Types")]
[assembly: AssemblyDescription("Contains types to enable the plugin architecture in NuGet Package Explorer.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("3.7.0.0")]
[assembly: AssemblyFileVersion("3.7.0.0")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8bdc7953-73c3-47d6-b0c5-41fda3d55e42")]``` |
f178ca9c-7d96-442c-8abf-68f337cfa521 | {
"language": "C#"
} | ```c#
using System.IO;
using System.Text;
using CSF.Screenplay.Reporting.Tests;
using CSF.Screenplay.Reporting.Tests.Autofixture;
using CSF.Screenplay.ReportModel;
using NUnit.Framework;
namespace CSF.Screenplay.Reporting.Tests
{
[TestFixture]
public class JsonReportRendererTests
{
[Test,AutoMoqData]
public void Write_can_create_a_document_without_crashing([RandomReport] Report report)
{
// Arrange
using(var writer = GetReportOutput())
{
var sut = new JsonReportRenderer(writer);
// Act & assert
Assert.DoesNotThrow(() => sut.Render(report));
}
}
TextWriter GetReportOutput()
{
// Uncomment this line to write the report to a file instead of a throwaway string
return new StreamWriter("JsonReportRendererTests.json");
//var sb = new StringBuilder();
//return new StringWriter(sb);
}
}
}
```
Change test back to using a string builder | ```c#
using System.IO;
using System.Text;
using CSF.Screenplay.Reporting.Tests;
using CSF.Screenplay.Reporting.Tests.Autofixture;
using CSF.Screenplay.ReportModel;
using NUnit.Framework;
namespace CSF.Screenplay.Reporting.Tests
{
[TestFixture]
public class JsonReportRendererTests
{
[Test,AutoMoqData]
public void Write_can_create_a_document_without_crashing([RandomReport] Report report)
{
// Arrange
using(var writer = GetReportOutput())
{
var sut = new JsonReportRenderer(writer);
// Act & assert
Assert.DoesNotThrow(() => sut.Render(report));
}
}
TextWriter GetReportOutput()
{
// Uncomment this line to write the report to a file instead of a throwaway string
//return new StreamWriter("JsonReportRendererTests.json");
var sb = new StringBuilder();
return new StringWriter(sb);
}
}
}
``` |
9146663c-34bd-471f-ab16-7eb21ce21b42 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using RabbitMQ.Client.Exceptions;
namespace EasyNetQ.Hosepipe
{
public interface IQueueRetreival {
IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters);
}
public class QueueRetreival : IQueueRetreival
{
public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters)
{
using (var connection = HosepipeConnection.FromParamters(parameters))
using (var channel = connection.CreateModel())
{
try
{
channel.QueueDeclarePassive(parameters.QueueName);
}
catch (OperationInterruptedException exception)
{
Console.WriteLine(exception.Message);
yield break;
}
var count = 0;
while (++count < parameters.NumberOfMessagesToRetrieve)
{
var basicGetResult = channel.BasicGet(parameters.QueueName, noAck: parameters.Purge);
if (basicGetResult == null) break; // no more messages on the queue
var properties = new MessageProperties(basicGetResult.BasicProperties);
var info = new MessageReceivedInfo(
"hosepipe",
basicGetResult.DeliveryTag,
basicGetResult.Redelivered,
basicGetResult.Exchange,
basicGetResult.RoutingKey,
parameters.QueueName);
yield return new HosepipeMessage(Encoding.UTF8.GetString(basicGetResult.Body), properties, info);
}
}
}
}
}```
Fix number of messages retrieved. Used to be n-1 | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using RabbitMQ.Client.Exceptions;
namespace EasyNetQ.Hosepipe
{
public interface IQueueRetreival {
IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters);
}
public class QueueRetreival : IQueueRetreival
{
public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters)
{
using (var connection = HosepipeConnection.FromParamters(parameters))
using (var channel = connection.CreateModel())
{
try
{
channel.QueueDeclarePassive(parameters.QueueName);
}
catch (OperationInterruptedException exception)
{
Console.WriteLine(exception.Message);
yield break;
}
var count = 0;
while (count++ < parameters.NumberOfMessagesToRetrieve)
{
var basicGetResult = channel.BasicGet(parameters.QueueName, noAck: parameters.Purge);
if (basicGetResult == null) break; // no more messages on the queue
var properties = new MessageProperties(basicGetResult.BasicProperties);
var info = new MessageReceivedInfo(
"hosepipe",
basicGetResult.DeliveryTag,
basicGetResult.Redelivered,
basicGetResult.Exchange,
basicGetResult.RoutingKey,
parameters.QueueName);
yield return new HosepipeMessage(Encoding.UTF8.GetString(basicGetResult.Body), properties, info);
}
}
}
}
}``` |
cd6580a0-e5cb-4a4c-a79b-e67a242ab30a | {
"language": "C#"
} | ```c#
using System;
using System.Linq.Expressions;
using Abp.Timing;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Abp.EntityFrameworkCore.ValueConverters
{
public class AbpDateTimeValueConverter : ValueConverter<DateTime?, DateTime?>
{
public AbpDateTimeValueConverter([CanBeNull] ConverterMappingHints mappingHints = default)
: base(Normalize, Normalize, mappingHints)
{
}
private static readonly Expression<Func<DateTime?, DateTime?>> Normalize = x =>
x.HasValue ? Clock.Normalize(x.Value) : x;
}
}```
Change the default value of the parameter initialization method. | ```c#
using System;
using System.Linq.Expressions;
using Abp.Timing;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Abp.EntityFrameworkCore.ValueConverters
{
public class AbpDateTimeValueConverter : ValueConverter<DateTime?, DateTime?>
{
public AbpDateTimeValueConverter([CanBeNull] ConverterMappingHints mappingHints = null)
: base(Normalize, Normalize, mappingHints)
{
}
private static readonly Expression<Func<DateTime?, DateTime?>> Normalize = x =>
x.HasValue ? Clock.Normalize(x.Value) : x;
}
}``` |
ef1699bd-a21f-47c8-b3a1-04c495952494 | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyTitle("Knapcode.StandardSerializer")]
[assembly: System.Runtime.InteropServices.ComVisible(false)]
[assembly: System.CLSCompliant(true)]
[assembly: System.Runtime.InteropServices.Guid("963e0295-1d98-4f44-aadc-8cb4ba91c613")]
[assembly: System.Reflection.AssemblyInformationalVersion("1.0.0.0-9c82a0d-dirty")]
[assembly: System.Reflection.AssemblyVersion("1.0.0.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")]
```
Change the assembly version to "base" | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyTitle("Knapcode.StandardSerializer")]
[assembly: System.Runtime.InteropServices.ComVisible(false)]
[assembly: System.CLSCompliant(true)]
[assembly: System.Runtime.InteropServices.Guid("963e0295-1d98-4f44-aadc-8cb4ba91c613")]
[assembly: System.Reflection.AssemblyInformationalVersion("1.0.0.0-base")]
[assembly: System.Reflection.AssemblyVersion("1.0.0.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")]
``` |
d48eb551-dbd8-477b-8330-912b21ff3a97 | {
"language": "C#"
} | ```c#
@model IList<User>
@{
ViewData["Title"] = "List Non Admin Users";
}
<div class="col">
<table id="table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
<th>Client Id</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>
<a class="btn btn-default" asp-action="EditUser" asp-route-Id="@user.Id" >Edit</a>
</td>
<td>@user.Name</td>
<td>@user.Email</td>
<td>@user.ClientId</td>
<td>@user.Phone</td>
</tr>
}
</tbody>
</table>
</div>
@section AdditionalStyles
{
@{ await Html.RenderPartialAsync("_DataTableStylePartial"); }
}
@section Scripts
{
@{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); }
<script type="text/javascript">
$(function () {
$("#table").dataTable({
"sorting": [[2, "desc"]],
"pageLength": 100,
});
});
</script>
}
```
Fix sorting and searching on table | ```c#
@model IList<User>
@{
ViewData["Title"] = "List Non Admin Users";
}
<div class="col">
<table id="table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
<th>Client Id</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>
<a class="btn btn-default" asp-action="EditUser" asp-route-Id="@user.Id" >Edit</a>
</td>
<td>@user.Name</td>
<td>@user.Email</td>
<td>@user.ClientId</td>
<td>@user.Phone</td>
</tr>
}
</tbody>
</table>
</div>
@section AdditionalStyles
{
@{ await Html.RenderPartialAsync("_DataTableStylePartial"); }
}
@section Scripts
{
@{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); }
<script type="text/javascript">
$(function () {
$("#table").dataTable({
"sorting": [[2, "desc"]],
"pageLength": 100,
"columnDefs": [
{ "orderable": false, "targets": [0] },
{ "searchable":false, "targets": 0 }
]
});
});
</script>
}
``` |
8d210e6e-d88d-4a2e-8d53-e18b77736e4b | {
"language": "C#"
} | ```c#
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
```
Set the document language to English | ```c#
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
``` |
4bb6d987-7eac-4457-a78e-40ea738d57b3 | {
"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 System;
using System.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.Sdl
{
public class SdlClipboard : Clipboard
{
private const string lib = "libSDL2-2.0";
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)]
internal static extern void SDL_free(IntPtr ptr);
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)]
internal static extern IntPtr SDL_GetClipboardText();
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)]
internal static extern int SDL_SetClipboardText(string text);
public override string GetText()
{
IntPtr ptrToText = SDL_GetClipboardText();
string text = Marshal.PtrToStringAnsi(ptrToText);
SDL_free(ptrToText);
return text;
}
public override void SetText(string selectedText)
{
SDL_SetClipboardText(selectedText);
}
}
}
```
Add doc for what happens when getting clipboard text fails (SDL) | ```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 System;
using System.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.Sdl
{
public class SdlClipboard : Clipboard
{
private const string lib = "libSDL2-2.0";
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)]
internal static extern void SDL_free(IntPtr ptr);
/// <returns>Returns the clipboard text on success or <see cref="IntPtr.Zero"/> on failure. </returns>
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)]
internal static extern IntPtr SDL_GetClipboardText();
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)]
internal static extern int SDL_SetClipboardText(string text);
public override string GetText()
{
IntPtr ptrToText = SDL_GetClipboardText();
string text = Marshal.PtrToStringAnsi(ptrToText);
SDL_free(ptrToText);
return text;
}
public override void SetText(string selectedText)
{
SDL_SetClipboardText(selectedText);
}
}
}
``` |
017fc72f-eeb2-4b3d-a214-88fd4c30b114 | {
"language": "C#"
} | ```c#
using Hangfire.Mongo.Database;
using MongoDB.Driver;
using System;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;
namespace Hangfire.Mongo.MongoUtils
{
/// <summary>
/// Helper utilities to work with Mongo database
/// </summary>
public static class MongoExtensions
{
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="database">Mongo database</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this IMongoDatabase database)
{
try
{
dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1)));
return ((DateTime)serverStatus.localTime).ToUniversalTime();
}
catch (MongoException)
{
return DateTime.UtcNow;
}
}
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="dbContext">Hangfire database context</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext)
{
return GetServerTimeUtc(dbContext.Database);
}
}
}```
Optimize query for server time. (not throwing exception) | ```c#
using Hangfire.Mongo.Database;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;
namespace Hangfire.Mongo.MongoUtils
{
/// <summary>
/// Helper utilities to work with Mongo database
/// </summary>
public static class MongoExtensions
{
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="database">Mongo database</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this IMongoDatabase database)
{
dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1)));
object localTime;
if (((IDictionary<string, object>)serverStatus).TryGetValue("localTime", out localTime))
{
return ((DateTime)localTime).ToUniversalTime();
}
return DateTime.UtcNow;
}
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="dbContext">Hangfire database context</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext)
{
return GetServerTimeUtc(dbContext.Database);
}
}
}``` |
333811f4-2aa3-4831-a0aa-a51f6ccebb62 | {
"language": "C#"
} | ```c#
namespace Nilgiri.Examples
{
using Xunit;
using Nilgiri.Tests.Common;
using static Nilgiri.ExpectStyle;
public partial class ExampleOf_Should
{
public class Not_Be_Ok
{
[Fact]
public void Int32()
{
_(0).Should.Not.Be.Ok();
_(() => 0).Should.Not.Be.Ok();
}
[Fact]
public void Nullable()
{
_((bool?)false).Should.Not.Be.Ok();
_(() => (bool?)false).Should.Not.Be.Ok();
}
[Fact]
public void String()
{
_((string)null).Should.Not.Be.Ok();
_(() => (string)null).Should.Not.Be.Ok();
_(System.String.Empty).Should.Not.Be.Ok();
_(() => System.String.Empty).Should.Not.Be.Ok();
_("").Should.Not.Be.Ok();
_(() => "").Should.Not.Be.Ok();
_(" ").Should.Not.Be.Ok();
_(() => " ").Should.Not.Be.Ok();
}
[Fact]
public void ReferenceTypes()
{
_((StubClass)null).Should.Not.Be.Ok();
_(() => (StubClass)null).Should.Not.Be.Ok();
}
}
}
}
```
Fix the using. Sometimes atom can be... | ```c#
namespace Nilgiri.Examples
{
using Xunit;
using Nilgiri.Tests.Common;
using static Nilgiri.ShouldStyle;
public partial class ExampleOf_Should
{
public class Not_Be_Ok
{
[Fact]
public void Int32()
{
_(0).Should.Not.Be.Ok();
_(() => 0).Should.Not.Be.Ok();
}
[Fact]
public void Nullable()
{
_((bool?)false).Should.Not.Be.Ok();
_(() => (bool?)false).Should.Not.Be.Ok();
}
[Fact]
public void String()
{
_((string)null).Should.Not.Be.Ok();
_(() => (string)null).Should.Not.Be.Ok();
_(System.String.Empty).Should.Not.Be.Ok();
_(() => System.String.Empty).Should.Not.Be.Ok();
_("").Should.Not.Be.Ok();
_(() => "").Should.Not.Be.Ok();
_(" ").Should.Not.Be.Ok();
_(() => " ").Should.Not.Be.Ok();
}
[Fact]
public void ReferenceTypes()
{
_((StubClass)null).Should.Not.Be.Ok();
_(() => (StubClass)null).Should.Not.Be.Ok();
}
}
}
}
``` |
412ce05e-8fad-424c-9ba1-012e0851928a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ProjectTracker.Library.Admin;
namespace PTWpf
{
/// <summary>
/// Interaction logic for RolesEdit.xaml
/// </summary>
public partial class RolesEdit : EditForm
{
public RolesEdit()
{
InitializeComponent();
Csla.Wpf.CslaDataProvider dp = this.FindResource("RoleList") as Csla.Wpf.CslaDataProvider;
dp.DataChanged += new EventHandler(base.DataChanged);
}
protected override void ApplyAuthorization()
{
this.AuthPanel.Refresh();
if (Csla.Security.AuthorizationRules.CanEditObject(typeof(Roles)))
{
this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbTemplate"];
}
else
{
this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbroTemplate"];
((Csla.Wpf.CslaDataProvider)this.FindResource("RoleList")).Cancel();
}
}
}
}
```
Use the new Delete command support in CslaDataProvider. | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ProjectTracker.Library.Admin;
namespace PTWpf
{
/// <summary>
/// Interaction logic for RolesEdit.xaml
/// </summary>
public partial class RolesEdit : EditForm
{
public RolesEdit()
{
InitializeComponent();
Csla.Wpf.CslaDataProvider dp = this.FindResource("RoleList") as Csla.Wpf.CslaDataProvider;
dp.DataChanged += new EventHandler(base.DataChanged);
}
protected override void ApplyAuthorization()
{
if (Csla.Security.AuthorizationRules.CanEditObject(typeof(Roles)))
{
this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbTemplate"];
}
else
{
this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbroTemplate"];
((Csla.Wpf.CslaDataProvider)this.FindResource("RoleList")).Cancel();
}
}
}
}
``` |
5ab6ef83-62a2-41a6-a4c8-2057cad0c67c | {
"language": "C#"
} | ```c#
namespace nuserv.Utility
{
using System.Net.Http;
using System.Web;
using System.Web.Http.Routing;
public class HttpRouteDataResolver : IHttpRouteDataResolver
{
#region Public Methods and Operators
public IHttpRouteData Resolve()
{
if (HttpContext.Current != null)
{
var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
return requestMessage.GetRouteData();
}
return null;
}
#endregion
}
}```
Implement RouteData resolvement while in wcf context | ```c#
namespace nuserv.Utility
{
#region Usings
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Routing;
#endregion
public class HttpRouteDataResolver : IHttpRouteDataResolver
{
#region Public Methods and Operators
public IHttpRouteData Resolve()
{
if (HttpContext.Current != null)
{
if (HttpContext.Current.Items.Contains(""))
{
var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
if (requestMessage != null)
{
return requestMessage.GetRouteData();
}
}
else
{
return new RouteData(HttpContext.Current.Request.RequestContext.RouteData);
}
}
return null;
}
#endregion
private class RouteData : IHttpRouteData
{
#region Fields
private readonly System.Web.Routing.RouteData originalRouteData;
#endregion
#region Constructors and Destructors
public RouteData(System.Web.Routing.RouteData routeData)
{
if (routeData == null)
{
throw new ArgumentNullException("routeData");
}
this.originalRouteData = routeData;
this.Route = null;
}
#endregion
#region Public Properties
public IHttpRoute Route { get; private set; }
public IDictionary<string, object> Values
{
get
{
return this.originalRouteData.Values;
}
}
#endregion
}
}
}``` |
ed1e39ac-8377-4959-b1e7-27ae02dac6de | {
"language": "C#"
} | ```c#
namespace NServiceBus
{
using Settings;
using Features;
using Persistence;
using Persistence.Sql;
/// <summary>
/// The <see cref="PersistenceDefinition"/> for the SQL Persistence.
/// </summary>
public class SqlPersistence : PersistenceDefinition
{
/// <summary>
/// Initializes a new instance of <see cref="SqlPersistence"/>.
/// </summary>
public SqlPersistence()
{
Supports<StorageType.Outbox>(s =>
{
EnableSession(s);
s.EnableFeatureByDefault<SqlOutboxFeature>();
});
Supports<StorageType.Timeouts>(s =>
{
s.EnableFeatureByDefault<SqlTimeoutFeature>();
});
Supports<StorageType.Sagas>(s =>
{
EnableSession(s);
s.EnableFeatureByDefault<SqlSagaFeature>();
s.AddUnrecoverableException(typeof(SerializationException));
});
Supports<StorageType.Subscriptions>(s =>
{
s.EnableFeatureByDefault<SqlSubscriptionFeature>();
});
Defaults(s =>
{
var dialect = s.GetSqlDialect();
var diagnostics = dialect.GetCustomDialectDiagnosticsInfo();
s.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.SqlDialect", new
{
Name = dialect.Name,
CustomDiagnostics = diagnostics
});
s.EnableFeatureByDefault<InstallerFeature>();
});
}
static void EnableSession(SettingsHolder s)
{
s.EnableFeatureByDefault<StorageSessionFeature>();
}
}
}```
Make sure to only invoke defaults once | ```c#
namespace NServiceBus
{
using Settings;
using Features;
using Persistence;
using Persistence.Sql;
/// <summary>
/// The <see cref="PersistenceDefinition"/> for the SQL Persistence.
/// </summary>
public class SqlPersistence : PersistenceDefinition
{
/// <summary>
/// Initializes a new instance of <see cref="SqlPersistence"/>.
/// </summary>
public SqlPersistence()
{
Supports<StorageType.Outbox>(s =>
{
EnableSession(s);
s.EnableFeatureByDefault<SqlOutboxFeature>();
});
Supports<StorageType.Timeouts>(s =>
{
s.EnableFeatureByDefault<SqlTimeoutFeature>();
});
Supports<StorageType.Sagas>(s =>
{
EnableSession(s);
s.EnableFeatureByDefault<SqlSagaFeature>();
s.AddUnrecoverableException(typeof(SerializationException));
});
Supports<StorageType.Subscriptions>(s =>
{
s.EnableFeatureByDefault<SqlSubscriptionFeature>();
});
Defaults(s =>
{
var defaultsAppliedSettingsKey = "NServiceBus.Persistence.Sql.DefaultApplied";
if (s.HasSetting(defaultsAppliedSettingsKey))
{
return;
}
var dialect = s.GetSqlDialect();
var diagnostics = dialect.GetCustomDialectDiagnosticsInfo();
s.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.SqlDialect", new
{
Name = dialect.Name,
CustomDiagnostics = diagnostics
});
s.EnableFeatureByDefault<InstallerFeature>();
s.Set(defaultsAppliedSettingsKey, true);
});
}
static void EnableSession(SettingsHolder s)
{
s.EnableFeatureByDefault<StorageSessionFeature>();
}
}
}``` |
3c839bfb-9873-46b8-8c93-87c6f9580d0d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using ExpressRunner.Api;
namespace ExpressRunner
{
public class TestItem : PropertyChangedBase, IRunnableTest
{
public string Name
{
get { return Test.Name; }
}
private readonly BindableCollection<TestRun> runs = new BindableCollection<TestRun>();
public IObservableCollection<TestRun> Runs
{
get { return runs; }
}
private TestStatus status = TestStatus.NotRun;
public TestStatus Status
{
get { return status; }
private set
{
if (status != value)
{
status = value;
NotifyOfPropertyChange("Status");
}
}
}
private readonly Test test;
public Test Test
{
get { return test; }
}
public TestItem(Test test)
{
if (test == null)
throw new ArgumentNullException("test");
this.test = test;
}
public void RecordRun(TestRun run)
{
runs.Add(run);
UpdateStatus(run);
}
private void UpdateStatus(TestRun run)
{
if (run.Status == TestStatus.Failed)
Status = TestStatus.Failed;
else if (Status == TestStatus.NotRun)
Status = run.Status;
}
}
}
```
Change order of update operation in RecordRun | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using ExpressRunner.Api;
namespace ExpressRunner
{
public class TestItem : PropertyChangedBase, IRunnableTest
{
public string Name
{
get { return Test.Name; }
}
private readonly BindableCollection<TestRun> runs = new BindableCollection<TestRun>();
public IObservableCollection<TestRun> Runs
{
get { return runs; }
}
private TestStatus status = TestStatus.NotRun;
public TestStatus Status
{
get { return status; }
private set
{
if (status != value)
{
status = value;
NotifyOfPropertyChange("Status");
}
}
}
private readonly Test test;
public Test Test
{
get { return test; }
}
public TestItem(Test test)
{
if (test == null)
throw new ArgumentNullException("test");
this.test = test;
}
public void RecordRun(TestRun run)
{
UpdateStatus(run);
runs.Add(run);
}
private void UpdateStatus(TestRun run)
{
if (run.Status == TestStatus.Failed)
Status = TestStatus.Failed;
else if (Status == TestStatus.NotRun)
Status = run.Status;
}
}
}
``` |
52d6c540-bc24-468a-8be8-d72ca1ba5a46 | {
"language": "C#"
} | ```c#
namespace Fixie.Execution
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class MethodDiscoverer
{
readonly Filter filter;
readonly IReadOnlyList<Func<MethodInfo, bool>> testMethodConditions;
public MethodDiscoverer(Filter filter, Convention convention)
{
this.filter = filter;
testMethodConditions = convention.Config.TestMethodConditions;
}
public IReadOnlyList<MethodInfo> TestMethods(Type testClass)
{
try
{
bool testClassIsDisposable = IsDisposable(testClass);
return testClass
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(method => method.DeclaringType != typeof(object))
.Where(method => !(testClassIsDisposable && HasDisposeSignature(method)))
.Where(IsMatch)
.Where(method => filter.IsSatisfiedBy(new MethodGroup(testClass, method)))
.ToArray();
}
catch (Exception exception)
{
throw new Exception(
"Exception thrown while attempting to run a custom method-discovery predicate. " +
"Check the inner exception for more details.", exception);
}
}
bool IsMatch(MethodInfo candidate)
=> testMethodConditions.All(condition => condition(candidate));
static bool IsDisposable(Type type)
=> type.GetInterfaces().Any(interfaceType => interfaceType == typeof(IDisposable));
static bool HasDisposeSignature(MethodInfo method)
=> method.Name == "Dispose" && method.IsVoid() && method.GetParameters().Length == 0;
}
}```
Optimize the detection of IDisposable test classes. Array.Contains performs fewer allocations than the LINQ Any extension method. | ```c#
namespace Fixie.Execution
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class MethodDiscoverer
{
readonly Filter filter;
readonly IReadOnlyList<Func<MethodInfo, bool>> testMethodConditions;
public MethodDiscoverer(Filter filter, Convention convention)
{
this.filter = filter;
testMethodConditions = convention.Config.TestMethodConditions;
}
public IReadOnlyList<MethodInfo> TestMethods(Type testClass)
{
try
{
bool testClassIsDisposable = IsDisposable(testClass);
return testClass
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(method => method.DeclaringType != typeof(object))
.Where(method => !(testClassIsDisposable && HasDisposeSignature(method)))
.Where(IsMatch)
.Where(method => filter.IsSatisfiedBy(new MethodGroup(testClass, method)))
.ToArray();
}
catch (Exception exception)
{
throw new Exception(
"Exception thrown while attempting to run a custom method-discovery predicate. " +
"Check the inner exception for more details.", exception);
}
}
bool IsMatch(MethodInfo candidate)
=> testMethodConditions.All(condition => condition(candidate));
static bool IsDisposable(Type type)
=> type.GetInterfaces().Contains(typeof(IDisposable));
static bool HasDisposeSignature(MethodInfo method)
=> method.Name == "Dispose" && method.IsVoid() && method.GetParameters().Length == 0;
}
}``` |
ddaed703-d32a-428f-8bd7-9da4c368d4d6 | {
"language": "C#"
} | ```c#
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace AlertSample
{
using System;
internal sealed class Program
{
private static void Main(string[] args)
{
Alert alert = new Alert("AlertSample", 5.0d, 10.0d);
try
{
alert.Start();
}
catch (Exception e)
{
Console.WriteLine("ERROR: {0}", e);
throw;
}
finally
{
alert.Stop();
}
}
}
}
```
Add parent and child app skeleton | ```c#
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace AlertSample
{
using System;
internal sealed class Program
{
private static int Main(string[] args)
{
if (args.Length == 0)
{
return RunParent();
}
else if (args.Length == 1)
{
return RunChild(args[0]);
}
else
{
Console.WriteLine("Invalid arguments.");
return 1;
}
}
private static int RunParent()
{
Alert alert = new Alert("AlertSample", 5.0d, 10.0d);
try
{
alert.Start();
}
catch (Exception e)
{
Console.WriteLine("ERROR: {0}", e);
throw;
}
finally
{
alert.Stop();
}
return 0;
}
private static int RunChild(string name)
{
Console.WriteLine("TODO: " + name);
return 0;
}
}
}
``` |
c3da5651-c208-430a-be62-ddb89e26297f | {
"language": "C#"
} | ```c#
using System.ServiceModel;
namespace TfsHipChat
{
class Program
{
static void Main()
{
using (var host = new ServiceHost(typeof(CheckinEventService)))
{
host.Open();
}
}
}
}
```
Add blocking statement to ensure service remains alive | ```c#
using System;
using System.ServiceModel;
namespace TfsHipChat
{
class Program
{
static void Main()
{
using (var host = new ServiceHost(typeof(CheckinEventService)))
{
host.Open();
Console.WriteLine("TfsHipChat started!");
Console.ReadLine();
}
}
}
}
``` |
cfa99ea4-c68e-4129-ad3b-ce07b8f27df2 | {
"language": "C#"
} | ```c#
using System.Diagnostics;
namespace Cake.Core.Polyfill
{
internal static class ProcessHelper
{
public static void SetEnvironmentVariable(ProcessStartInfo info, string key, string value)
{
#if NETCORE
info.Environment[key] = value;
#else
info.EnvironmentVariables[key] = value;
#endif
}
}
}
```
Address ProcessStartInfo envvar case sensitivite issue | ```c#
using System;
using System.Diagnostics;
using System.Linq;
namespace Cake.Core.Polyfill
{
internal static class ProcessHelper
{
public static void SetEnvironmentVariable(ProcessStartInfo info, string key, string value)
{
#if NETCORE
var envKey = info.Environment.Keys.FirstOrDefault(exisitingKey => StringComparer.OrdinalIgnoreCase.Equals(exisitingKey, key)) ?? key;
info.Environment[envKey] = value;
#else
var envKey = info.EnvironmentVariables.Keys.Cast<string>().FirstOrDefault(existingKey => StringComparer.OrdinalIgnoreCase.Equals(existingKey, key)) ?? key;
info.EnvironmentVariables[key] = value;
#endif
}
}
}
``` |
d887b9de-fe3c-4881-bcc3-b9158fa9cd18 | {
"language": "C#"
} | ```c#
using BlueMonkey.ExpenceServices;
using BlueMonkey.ExpenceServices.Local;
using BlueMonkey.Model;
using Prism.Unity;
using BlueMonkey.Views;
using Xamarin.Forms;
using Microsoft.Practices.Unity;
namespace BlueMonkey
{
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("NavigationPage/MainPage");
}
protected override void RegisterTypes()
{
Container.RegisterType<IExpenseService, ExpenseService>(new ContainerControlledLifetimeManager());
Container.RegisterType<IEditReport, EditReport>(new ContainerControlledLifetimeManager());
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<MainPage>();
Container.RegisterTypeForNavigation<AddExpensePage>();
Container.RegisterTypeForNavigation<ExpenseListPage>();
Container.RegisterTypeForNavigation<ChartPage>();
Container.RegisterTypeForNavigation<ReportPage>();
Container.RegisterTypeForNavigation<ReceiptPage>();
Container.RegisterTypeForNavigation<AddReportPage>();
Container.RegisterTypeForNavigation<ReportListPage>();
Container.RegisterTypeForNavigation<ExpenseSelectionPage>();
Container.RegisterTypeForNavigation<LoginPage>();
}
}
}
```
Set initial page to LoginPage | ```c#
using BlueMonkey.ExpenceServices;
using BlueMonkey.ExpenceServices.Local;
using BlueMonkey.Model;
using Prism.Unity;
using BlueMonkey.Views;
using Xamarin.Forms;
using Microsoft.Practices.Unity;
namespace BlueMonkey
{
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("LoginPage");
}
protected override void RegisterTypes()
{
Container.RegisterType<IExpenseService, ExpenseService>(new ContainerControlledLifetimeManager());
Container.RegisterType<IEditReport, EditReport>(new ContainerControlledLifetimeManager());
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<MainPage>();
Container.RegisterTypeForNavigation<AddExpensePage>();
Container.RegisterTypeForNavigation<ExpenseListPage>();
Container.RegisterTypeForNavigation<ChartPage>();
Container.RegisterTypeForNavigation<ReportPage>();
Container.RegisterTypeForNavigation<ReceiptPage>();
Container.RegisterTypeForNavigation<AddReportPage>();
Container.RegisterTypeForNavigation<ReportListPage>();
Container.RegisterTypeForNavigation<ExpenseSelectionPage>();
Container.RegisterTypeForNavigation<LoginPage>();
}
}
}
``` |
38324e25-ad02-4c6f-8396-c7eea58d4104 | {
"language": "C#"
} | ```c#
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Batch.Models;
using System.Management.Automation;
using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants;
namespace Microsoft.Azure.Commands.Batch
{
[Cmdlet(VerbsCommon.Get, Constants.AzureRmBatchLocationQuotas), OutputType(typeof(PSBatchLocationQuotas))]
[Alias("Get-AzureRmBatchSubscriptionQuotas")]
public class GetBatchLocationQuotasCommand : BatchCmdletBase
{
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The region to get the quotas of the subscription in the Batch Service from.")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
public override void ExecuteCmdlet()
{
PSBatchLocationQuotas quotas = BatchClient.GetLocationQuotas(this.Location);
WriteObject(quotas);
}
}
}
```
Add comment to backwards compat alias | ```c#
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Batch.Models;
using System.Management.Automation;
using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants;
namespace Microsoft.Azure.Commands.Batch
{
[Cmdlet(VerbsCommon.Get, Constants.AzureRmBatchLocationQuotas), OutputType(typeof(PSBatchLocationQuotas))]
// This alias was added in 10/2016 for backwards compatibility
[Alias("Get-AzureRmBatchSubscriptionQuotas")]
public class GetBatchLocationQuotasCommand : BatchCmdletBase
{
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The region to get the quotas of the subscription in the Batch Service from.")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
public override void ExecuteCmdlet()
{
PSBatchLocationQuotas quotas = BatchClient.GetLocationQuotas(this.Location);
WriteObject(quotas);
}
}
}
``` |
b90c1071-f1d3-4208-b0ce-301eeb1c80fd | {
"language": "C#"
} | ```c#
using Atlassian.Jira;
using TicketTimer.Core.Infrastructure;
using TicketTimer.Jira.Extensions;
namespace TicketTimer.Jira.Services
{
public class DefaultJiraService : JiraService
{
private readonly WorkItemStore _workItemStore;
// TODO Insert correct parameters
public Atlassian.Jira.Jira JiraClient => Atlassian.Jira.Jira.CreateRestClient("JiraUrl", "JiraUserName", "JiraPassword");
public DefaultJiraService(WorkItemStore workItemStore)
{
_workItemStore = workItemStore;
}
public void WriteEntireArchive()
{
var archive = _workItemStore.GetState().WorkItemArchive;
foreach (var workItem in archive)
{
// TODO Check if work item is jira-item.
TrackTime(workItem);
}
}
private void TrackTime(WorkItem workItem)
{
var workLog = new Worklog(workItem.Duration.ToJiraFormat(), workItem.Started.Date, workItem.Comment);
JiraClient.Issues.AddWorklogAsync(workItem.TicketNumber, workLog);
}
}
}
```
Check if the workitem if a jira issue, before logging time. | ```c#
using Atlassian.Jira;
using TicketTimer.Core.Infrastructure;
using TicketTimer.Jira.Extensions;
namespace TicketTimer.Jira.Services
{
public class DefaultJiraService : JiraService
{
private readonly WorkItemStore _workItemStore;
// TODO Insert correct parameters
public Atlassian.Jira.Jira JiraClient => Atlassian.Jira.Jira.CreateRestClient("JiraUrl", "JiraUserName", "JiraPassword");
public DefaultJiraService(WorkItemStore workItemStore)
{
_workItemStore = workItemStore;
}
public async void WriteEntireArchive()
{
var archive = _workItemStore.GetState().WorkItemArchive;
foreach (var workItem in archive)
{
var jiraIssue = await JiraClient.Issues.GetIssueAsync(workItem.TicketNumber);
if (jiraIssue != null)
{
TrackTime(workItem);
}
}
}
private void TrackTime(WorkItem workItem)
{
var workLog = new Worklog(workItem.Duration.ToJiraFormat(), workItem.Started.Date, workItem.Comment);
JiraClient.Issues.AddWorklogAsync(workItem.TicketNumber, workLog);
}
}
}
``` |
3e0fde15-78d3-4895-97de-5f2218252c6e | {
"language": "C#"
} | ```c#
namespace ScriptNET {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
internal class TypeCoercion {
// Handle type coercion to bool for Javascript-style if(foo) statements.
static public object CoerceToBool(object obj) {
if (obj is bool) {
// Do nothing, we're fine.
} else if (obj is string) {
// A non-empty string is true.
obj = !string.IsNullOrEmpty(obj as string);
} else {
// Give the binder a chance to splice in a bool coercion.
var equalityMethod = Runtime.RuntimeHost.Binder.BindToMethod(obj, "IsTrue", null, new object[0]);
if (equalityMethod != null) {
var result = equalityMethod.Invoke(null, new object[0]);
if (result is bool)
obj = (bool)result;
else
obj = obj != null;
} else {
// A non-null object is true.
obj = obj != null;
}
}
return obj;
}
}
}
```
Make bool type coercion work with arrays, and improve handling of non-null objects as expression arguments to unary ! and such | ```c#
namespace ScriptNET {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
internal class TypeCoercion {
// Handle type coercion to bool for Javascript-style if(foo) statements.
static public object CoerceToBool(object obj) {
if (obj is bool) {
// Do nothing, we're fine.
} else if (obj is string) {
// A non-empty string is true.
obj = !string.IsNullOrEmpty(obj as string);
} else if (obj is Array) {
obj = ((Array)obj).Length > 0;
} else if (obj == null) {
obj = false;
} else {
// Give the binder a chance to splice in a bool coercion.
var equalityMethod = Runtime.RuntimeHost.Binder.BindToMethod(obj, "IsTrue", null, new object[0]);
if (equalityMethod != null) {
var result = equalityMethod.Invoke(null, new object[0]);
if (result is bool)
obj = (bool)result;
else
obj = obj != null;
}
}
// If all else fails...
if (!(obj is bool)) {
// A non-null object is true.
obj = obj != null;
}
return obj;
}
}
}
``` |
c67d81a3-875d-4486-ba2e-791933215dcf | {
"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.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using osu.Game.Database;
namespace osu.Game.Beatmaps
{
public class BeatmapSetInfo : IHasPrimaryKey, IHasFiles<BeatmapSetFileInfo>, ISoftDelete
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public int? OnlineBeatmapSetID { get; set; }
public BeatmapMetadata Metadata { get; set; }
public List<BeatmapInfo> Beatmaps { get; set; }
[NotMapped]
public BeatmapSetOnlineInfo OnlineInfo { get; set; }
public double MaxStarDifficulty => Beatmaps?.Max(b => b.StarDifficulty) ?? 0;
[NotMapped]
public bool DeletePending { get; set; }
public string Hash { get; set; }
public string StoryboardFile => Files?.FirstOrDefault(f => f.Filename.EndsWith(".osb"))?.Filename;
public List<BeatmapSetFileInfo> Files { get; set; }
public override string ToString() => Metadata?.ToString() ?? base.ToString();
public bool Protected { get; set; }
}
}
```
Fix beatmaps importing with -1 as online set ID | ```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.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using osu.Game.Database;
namespace osu.Game.Beatmaps
{
public class BeatmapSetInfo : IHasPrimaryKey, IHasFiles<BeatmapSetFileInfo>, ISoftDelete
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
private int? onlineBeatmapSetID;
public int? OnlineBeatmapSetID
{
get { return onlineBeatmapSetID; }
set { onlineBeatmapSetID = value > 0 ? value : null; }
}
public BeatmapMetadata Metadata { get; set; }
public List<BeatmapInfo> Beatmaps { get; set; }
[NotMapped]
public BeatmapSetOnlineInfo OnlineInfo { get; set; }
public double MaxStarDifficulty => Beatmaps?.Max(b => b.StarDifficulty) ?? 0;
[NotMapped]
public bool DeletePending { get; set; }
public string Hash { get; set; }
public string StoryboardFile => Files?.FirstOrDefault(f => f.Filename.EndsWith(".osb"))?.Filename;
public List<BeatmapSetFileInfo> Files { get; set; }
public override string ToString() => Metadata?.ToString() ?? base.ToString();
public bool Protected { get; set; }
}
}
``` |
dd04a28c-26aa-40ef-94c4-f514cd763e8c | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using Sdl.Community.GroupShareKit.Clients;
using Sdl.Community.GroupShareKit.Http;
namespace Sdl.Community.GroupShareKit.Tests.Integration
{
public static class Helper
{
public static async Task<GroupShareClient> GetGroupShareClient()
{
var groupShareUser = Environment.GetEnvironmentVariable("GROUPSHAREKIT_USERNAME");
var groupSharePassword = Environment.GetEnvironmentVariable("GROUPSHAREKIT_PASSWORD");
var token =
await
GroupShareClient.GetRequestToken(groupShareUser, groupSharePassword, BaseUri,
GroupShareClient.AllScopes);
var gsClient =
await
GroupShareClient.AuthenticateClient(token, groupShareUser, groupSharePassword,BaseUri,
GroupShareClient.AllScopes);
return gsClient;
}
public static Uri BaseUri => new Uri(Environment.GetEnvironmentVariable("GROUPSHAREKIT_BASEURI"));
public static string TestOrganization => Environment.GetEnvironmentVariable("GROUPSHAREKIT_TESTORGANIZATION");
}
}
```
Allow getting a user env variable | ```c#
using System;
using System.Threading.Tasks;
using Sdl.Community.GroupShareKit.Clients;
using Sdl.Community.GroupShareKit.Http;
namespace Sdl.Community.GroupShareKit.Tests.Integration
{
public static class Helper
{
public static string GetVariable(string key)
{
// by default it gets a process variable. Allow getting user as well
return Environment.GetEnvironmentVariable(key) ??
Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User);
}
public static async Task<GroupShareClient> GetGroupShareClient()
{
var groupShareUser = Helper.GetVariable("GROUPSHAREKIT_USERNAME");
var groupSharePassword = Helper.GetVariable("GROUPSHAREKIT_PASSWORD");
var token =
await
GroupShareClient.GetRequestToken(groupShareUser, groupSharePassword, BaseUri,
GroupShareClient.AllScopes);
var gsClient =
await
GroupShareClient.AuthenticateClient(token, groupShareUser, groupSharePassword,BaseUri,
GroupShareClient.AllScopes);
return gsClient;
}
public static Uri BaseUri => new Uri(Helper.GetVariable("GROUPSHAREKIT_BASEURI"));
public static string TestOrganization => Helper.GetVariable("GROUPSHAREKIT_TESTORGANIZATION");
}
}
``` |
4a650fe5-814b-4e7b-9c28-8f93a75c94ea | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnlabMvc.Extensions
{
public static class StringExtensions
{
public static string PaymentMethodDescription(this string value)
{
if (string.Equals(value, "uc", StringComparison.OrdinalIgnoreCase))
{
return "UC Account";
}
if (string.Equals(value, "creditcard", StringComparison.OrdinalIgnoreCase))
{
return "Credit Card";
}
return "Other";
}
public static string MaxLength(this string value, int maxLength, bool ellipsis = true)
{
if (string.IsNullOrWhiteSpace(value))
{
return value;
}
if (value.Length > maxLength)
{
if (ellipsis)
{
return $"{value.Substring(0, maxLength - 3)}...";
}
return value.Substring(0, maxLength);
}
return value;
}
}
}
```
Add a string extension to validate Email | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AnlabMvc.Extensions
{
public static class StringExtensions
{
const string emailRegex = @"^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$";
public static string PaymentMethodDescription(this string value)
{
if (string.Equals(value, "uc", StringComparison.OrdinalIgnoreCase))
{
return "UC Account";
}
if (string.Equals(value, "creditcard", StringComparison.OrdinalIgnoreCase))
{
return "Credit Card";
}
return "Other";
}
public static string MaxLength(this string value, int maxLength, bool ellipsis = true)
{
if (string.IsNullOrWhiteSpace(value))
{
return value;
}
if (value.Length > maxLength)
{
if (ellipsis)
{
return $"{value.Substring(0, maxLength - 3)}...";
}
return value.Substring(0, maxLength);
}
return value;
}
public static bool IsEmailValid(this string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return false;
}
return Regex.IsMatch(value.ToLower(), emailRegex);
}
}
}
``` |
8a2039cf-0cde-44a2-b752-36ef38654f23 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using System.IO;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
[ExportWorkspaceService(typeof(IAssemblySerializationInfoService), ServiceLayer.Host)]
[Shared]
internal class AssemblySerializationInfoService : IAssemblySerializationInfoService
{
public bool Serializable(Solution solution, string assemblyFilePath)
{
if (assemblyFilePath == null || !File.Exists(assemblyFilePath) || !ReferencePathUtilities.PartOfFrameworkOrReferencePaths(assemblyFilePath))
{
return false;
}
// if solution is not from a disk, just create one.
if (solution.FilePath == null || !File.Exists(solution.FilePath))
{
return false;
}
return true;
}
public bool TryGetSerializationPrefixAndVersion(Solution solution, string assemblyFilePath, out string prefix, out VersionStamp version)
{
prefix = FilePathUtilities.GetRelativePath(solution.FilePath, assemblyFilePath);
version = VersionStamp.Create(File.GetLastWriteTimeUtc(assemblyFilePath));
return true;
}
}
}
```
Allow indices to be stored for .net assemblies. | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using System.IO;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
[ExportWorkspaceService(typeof(IAssemblySerializationInfoService), ServiceLayer.Host)]
[Shared]
internal class AssemblySerializationInfoService : IAssemblySerializationInfoService
{
public bool Serializable(Solution solution, string assemblyFilePath)
{
if (assemblyFilePath == null || !File.Exists(assemblyFilePath))
{
return false;
}
// if solution is not from a disk, just create one.
if (solution.FilePath == null || !File.Exists(solution.FilePath))
{
return false;
}
return true;
}
public bool TryGetSerializationPrefixAndVersion(Solution solution, string assemblyFilePath, out string prefix, out VersionStamp version)
{
prefix = FilePathUtilities.GetRelativePath(solution.FilePath, assemblyFilePath);
version = VersionStamp.Create(File.GetLastWriteTimeUtc(assemblyFilePath));
return true;
}
}
}
``` |
3fcb79b2-a5ad-41d0-92bd-c1b585e0a133 | {
"language": "C#"
} | ```c#
using Cimbalino.Toolkit.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Kliva.Models;
using Kliva.Views;
using Windows.UI.Xaml.Controls;
namespace Kliva.ViewModels
{
public class SidePaneViewModel : KlivaBaseViewModel
{
private bool _isPaneOpen = true;
public bool IsPaneOpen
{
get { return _isPaneOpen; }
set { Set(() => IsPaneOpen, ref _isPaneOpen, value); }
}
private bool _isPaneVisible = true;
public bool IsPaneVisible
{
get { return _isPaneVisible; }
set { Set(() => IsPaneVisible, ref _isPaneVisible, value); }
}
private SplitViewDisplayMode _displayMode = SplitViewDisplayMode.CompactOverlay;
public SplitViewDisplayMode DisplayMode
{
get { return _displayMode; }
set { Set(() => DisplayMode, ref _displayMode, value); }
}
private RelayCommand _hamburgerCommand;
public RelayCommand HamburgerCommand => _hamburgerCommand ?? (_hamburgerCommand = new RelayCommand(() => this.IsPaneOpen = !this.IsPaneOpen));
private RelayCommand _settingsCommand;
public RelayCommand SettingsCommand => _settingsCommand ?? (_settingsCommand = new RelayCommand(() => _navigationService.Navigate<SettingsPage>()));
public SidePaneViewModel(INavigationService navigationService) : base(navigationService)
{
}
internal void ShowHide(bool show)
{
if (show)
this.DisplayMode = SplitViewDisplayMode.CompactOverlay;
else
this.DisplayMode = SplitViewDisplayMode.Inline;
this.IsPaneVisible = show;
}
}
}
```
Adjust pane when going to inline mode to close it | ```c#
using Cimbalino.Toolkit.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Kliva.Models;
using Kliva.Views;
using Windows.UI.Xaml.Controls;
namespace Kliva.ViewModels
{
public class SidePaneViewModel : KlivaBaseViewModel
{
private bool _isPaneOpen = false;
public bool IsPaneOpen
{
get { return _isPaneOpen; }
set { Set(() => IsPaneOpen, ref _isPaneOpen, value); }
}
private SplitViewDisplayMode _displayMode = SplitViewDisplayMode.CompactOverlay;
public SplitViewDisplayMode DisplayMode
{
get { return _displayMode; }
set { Set(() => DisplayMode, ref _displayMode, value); }
}
private RelayCommand _hamburgerCommand;
public RelayCommand HamburgerCommand => _hamburgerCommand ?? (_hamburgerCommand = new RelayCommand(() => this.IsPaneOpen = !this.IsPaneOpen));
private RelayCommand _settingsCommand;
public RelayCommand SettingsCommand => _settingsCommand ?? (_settingsCommand = new RelayCommand(() => _navigationService.Navigate<SettingsPage>()));
public SidePaneViewModel(INavigationService navigationService) : base(navigationService)
{
}
internal void ShowHide(bool show)
{
if (show)
this.DisplayMode = SplitViewDisplayMode.CompactOverlay;
else
{
this.DisplayMode = SplitViewDisplayMode.Inline;
this.IsPaneOpen = false;
}
}
}
}
``` |
9737ca2b-e33d-4a0f-893c-6a1faef99a7e | {
"language": "C#"
} | ```c#
using DotNetNuke.Entities.Portals;
using System;
using System.Linq;
namespace Dnn.PersonaBar.Library.Helper
{
public class PortalHelper
{
private static readonly IContentVerifier _contentVerifier = new ContentVerifier(PortalController.Instance, PortalGroupController.Instance);
[Obsolete("Deprecated in 9.2.1. Use IContentVerifier.IsContentExistsForRequestedPortal")]
public static bool IsContentExistsForRequestedPortal(int contentPortalId, PortalSettings portalSettings, bool checkForSiteGroup = false)
{
return _contentVerifier.IsContentExistsForRequestedPortal(contentPortalId, portalSettings, checkForSiteGroup);
}
}
}
```
Use the parameterless contructor from Obselete Portal Helper | ```c#
using DotNetNuke.Entities.Portals;
using System;
namespace Dnn.PersonaBar.Library.Helper
{
public class PortalHelper
{
private static readonly IContentVerifier _contentVerifier = new ContentVerifier();
[Obsolete("Deprecated in 9.2.1. Use IContentVerifier.IsContentExistsForRequestedPortal")]
public static bool IsContentExistsForRequestedPortal(int contentPortalId, PortalSettings portalSettings, bool checkForSiteGroup = false)
{
return _contentVerifier.IsContentExistsForRequestedPortal(contentPortalId, portalSettings, checkForSiteGroup);
}
}
}
``` |
efec4a73-95c7-4063-a773-0727bf433b28 | {
"language": "C#"
} | ```c#
namespace TestableFileSystem.Fakes.Tests.Specs.FakeWatcher
{
public abstract class WatcherSpecs
{
protected const int NotifyWaitTimeoutMilliseconds = 500;
protected const int SleepTimeToEnsureOperationHasArrivedAtWatcherConsumerLoop = 250;
// TODO: Add specs for File.Encrypt/Decrypt, File.Lock/Unlock, File.Replace, Begin+EndRead/Write
// TODO: Add specs for Directory.GetLogicalDrives
}
}
```
Increase timeout to prevent cibuild failures | ```c#
namespace TestableFileSystem.Fakes.Tests.Specs.FakeWatcher
{
public abstract class WatcherSpecs
{
protected const int NotifyWaitTimeoutMilliseconds = 1000;
protected const int SleepTimeToEnsureOperationHasArrivedAtWatcherConsumerLoop = 250;
// TODO: Add specs for File.Encrypt/Decrypt, File.Lock/Unlock, File.Replace, Begin+EndRead/Write
// TODO: Add specs for Directory.GetLogicalDrives
}
}
``` |
c14ba06c-7128-4232-96db-51dd7384c766 | {
"language": "C#"
} | ```c#
@{
ViewBag.Title = "ComboLoad";
}
<div class="row">
<div class="col-md-12">
<h2>Example page for testing waits</h2>
<p>The following combo starts with a placeholder option and after 3 seconds updates with a new item.</p>
<select id="combo" >
<option>Placeholder</option>
</select>
</div>
</div>
@section scripts {
<script>
$(document).ready(function () {
var combo = $("#combo");
// Simulate loading the combo items from another source.
// Wait 3 seconds then update the combo.
setTimeout(function () {
combo.empty();
combo.append(
$("<option id=\"loaded\"></option>").text("Loaded")
);
},
3 * 1000);
});
</script>
}
```
Change the wait example to a mock login page. | ```c#
@{
ViewBag.Title = "ComboLoad";
}
<div class="row">
<div class="col-md-12">
<h2>Example page for testing waits</h2>
<p class="alert alert-danger" id="message" style="display:none"></p>
<div>
<div class="form-group">
<label for="username">Username</label>
<input type="email" class="form-control" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="button" class="btn btn-default" id="login">Log in</button>
</div>
</div>
</div>
@section scripts {
<script>
$(document).ready(function () {
var loginButton = $("#login");
loginButton.on("click", function () {
var usernameTxt = $("#username"),
username = usernameTxt[0].value
passwordTxt = $("#password"),
password = passwordTxt[0].value;
// Timeout to simulate making login request.
setTimeout(function () {
if (username === "user" && password === "password") {
window.location = "/";
}
else {
var messageContainer = $("#message");
messageContainer.text("Invalid username and password.")
messageContainer.css("display", "");
}
},
2 * 1000);
});
});
</script>
}
``` |
b17e40cd-6453-4fb7-96ea-4f0ef4b3c73a | {
"language": "C#"
} | ```c#
using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alteridem.GetChanges
{
class Program
{
static int Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options))
{
return -1;
}
AsyncContext.Run(() => MainAsync(options));
//Console.WriteLine("*** Press ENTER to Exit ***");
//Console.ReadLine();
return 0;
}
static async void MainAsync(Options options)
{
var github = new GitHubApi(options.Organization, options.Repository);
var milestones = await github.GetOpenMilestones();
foreach (var milestone in milestones.Where(m => m.DueOn != null && m.DueOn.Value.Subtract(DateTimeOffset.Now).TotalDays < 30))
{
var milestoneIssues = await github.GetClosedIssuesForMilestone(milestone);
DisplayIssuesForMilestone(options, milestone.Title, milestoneIssues);
}
}
static void DisplayIssuesForMilestone(Options options, string milestone, IEnumerable<Issue> issues)
{
Console.WriteLine("## {0}", milestone);
Console.WriteLine();
foreach (var issue in issues)
{
if(options.LinkIssues)
Console.WriteLine($" * [{issue.Number:####}](https://github.com/{options.Repository}/{options.Repository}/issues/{issue.Number}) {issue.Title}");
else
Console.WriteLine($" * {issue.Number:####} {issue.Title}");
}
Console.WriteLine();
}
}
}
```
Fix bug where repo name was used instead of organization in the links. | ```c#
using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alteridem.GetChanges
{
class Program
{
static int Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options))
{
return -1;
}
AsyncContext.Run(() => MainAsync(options));
//Console.WriteLine("*** Press ENTER to Exit ***");
//Console.ReadLine();
return 0;
}
static async void MainAsync(Options options)
{
var github = new GitHubApi(options.Organization, options.Repository);
var milestones = await github.GetOpenMilestones();
foreach (var milestone in milestones.Where(m => m.DueOn != null && m.DueOn.Value.Subtract(DateTimeOffset.Now).TotalDays < 30))
{
var milestoneIssues = await github.GetClosedIssuesForMilestone(milestone);
DisplayIssuesForMilestone(options, milestone.Title, milestoneIssues);
}
}
static void DisplayIssuesForMilestone(Options options, string milestone, IEnumerable<Issue> issues)
{
Console.WriteLine("## {0}", milestone);
Console.WriteLine();
foreach (var issue in issues)
{
if(options.LinkIssues)
Console.WriteLine($" * [{issue.Number:####}](https://github.com/{options.Organization}/{options.Repository}/issues/{issue.Number}) {issue.Title}");
else
Console.WriteLine($" * {issue.Number:####} {issue.Title}");
}
Console.WriteLine();
}
}
}
``` |
2bb4379f-cc5b-4366-a88b-35cee1261b69 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace BatteryCommander.Web.Models
{
public class RequestAccessModel
{
public String Name { get; set; }
public String Email { get; set; }
[Display(Name = "DOD ID")]
public String DoDId { get; set; }
public int Unit { get; set; }
public IEnumerable<SelectListItem> Units { get; set; }
}
}```
Add note about what your dod is | ```c#
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace BatteryCommander.Web.Models
{
public class RequestAccessModel
{
public String Name { get; set; }
public String Email { get; set; }
[Display(Name = "DOD ID (10 Digits, On Your CAC)")]
public String DoDId { get; set; }
public int Unit { get; set; }
public IEnumerable<SelectListItem> Units { get; set; }
}
}``` |
5bf6e0ee-5ce4-4404-b3ef-6b97e5f79eb9 | {
"language": "C#"
} | ```c#
@using SFA.DAS.EAS.Web
@using SFA.DAS.EAS.Web.Models
@model dynamic
@{
var viewModel = Model as OrchestratorResponse;
}
@if (!string.IsNullOrEmpty(viewModel?.FlashMessage?.Message) || !string.IsNullOrEmpty(viewModel?.FlashMessage?.SubMessage))
{
<div class="grid-row">
<div class="column-full">
<div class="@viewModel.FlashMessage.SeverityCssClass">
@if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline))
{
<h1 class="@(viewModel.FlashMessage.Severity == FlashMessageSeverityLevel.Error ? "bold-medium" : "bold-large")">@viewModel.FlashMessage.Headline</h1>
}
@if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message))
{
<p>@Html.Raw(viewModel.FlashMessage.Message)</p>
}
@if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage))
{
<p>@viewModel.FlashMessage.SubMessage</p>
}
@if (viewModel.FlashMessage.ErrorMessages.Any())
{
<ul class="error-summary-list">
@foreach (var errorMessage in viewModel.FlashMessage.ErrorMessages)
{
<li>
<a class="danger" href="#@errorMessage.Key">@errorMessage.Value</a>
</li>
}
</ul>
}
</div>
</div>
</div>
}```
Write out raw HTML if SubMessage contains any | ```c#
@using SFA.DAS.EAS.Web
@using SFA.DAS.EAS.Web.Models
@model dynamic
@{
var viewModel = Model as OrchestratorResponse;
}
@if (!string.IsNullOrEmpty(viewModel?.FlashMessage?.Message) || !string.IsNullOrEmpty(viewModel?.FlashMessage?.SubMessage))
{
<div class="grid-row">
<div class="column-full">
<div class="@viewModel.FlashMessage.SeverityCssClass">
@if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline))
{
<h1 class="@(viewModel.FlashMessage.Severity == FlashMessageSeverityLevel.Error ? "bold-medium" : "bold-large")">@viewModel.FlashMessage.Headline</h1>
}
@if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message))
{
<p>@Html.Raw(viewModel.FlashMessage.Message)</p>
}
@if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage))
{
<p>@Html.Raw(viewModel.FlashMessage.SubMessage)</p>
}
@if (viewModel.FlashMessage.ErrorMessages.Any())
{
<ul class="error-summary-list">
@foreach (var errorMessage in viewModel.FlashMessage.ErrorMessages)
{
<li>
<a class="danger" href="#@errorMessage.Key">@errorMessage.Value</a>
</li>
}
</ul>
}
</div>
</div>
</div>
}``` |
38046d2f-81f2-4bfa-86a8-d6a09d411b83 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections; using FastCollections;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Lockstep
{
public static class LSFSettingsManager
{
public const string DEFAULT_SETTINGS_NAME = "DefaultLockstepFrameworkSettings";
public const string SETTINGS_NAME = "LockstepFrameworkSettings";
static LSFSettings MainSettings;
static LSFSettingsManager()
{
LSFSettings settings = Resources.Load<LSFSettings>(SETTINGS_NAME);
#if UNITY_EDITOR
if (settings == null)
{
if (Application.isPlaying == false)
{
settings = ScriptableObject.CreateInstance <LSFSettings>();
if (!System.IO.Directory.Exists(Application.dataPath + "/Resources"))
AssetDatabase.CreateFolder("Assets", "Resources");
AssetDatabase.CreateAsset(settings, "Assets/Resources/" + SETTINGS_NAME + ".asset");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
} else
{
}
}
#endif
MainSettings = settings;
if (MainSettings == null)
{
settings = Resources.Load<LSFSettings>(DEFAULT_SETTINGS_NAME);
Debug.Log("No settings found. Loading default settings.");
}
}
public static LSFSettings GetSettings()
{
return MainSettings;
}
}
}```
Fix handling of deletion of settings file; | ```c#
using UnityEngine;
using System.Collections; using FastCollections;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Lockstep
{
public static class LSFSettingsManager
{
public const string DEFAULT_SETTINGS_NAME = "DefaultLockstepFrameworkSettings";
public const string SETTINGS_NAME = "LockstepFrameworkSettings";
static LSFSettings MainSettings;
static LSFSettingsManager () {
Initialize ();
}
static void Initialize()
{
LSFSettings settings = Resources.Load<LSFSettings>(SETTINGS_NAME);
#if UNITY_EDITOR
if (settings == null)
{
if (Application.isPlaying == false)
{
settings = ScriptableObject.CreateInstance <LSFSettings>();
if (!System.IO.Directory.Exists(Application.dataPath + "/Resources"))
AssetDatabase.CreateFolder("Assets", "Resources");
AssetDatabase.CreateAsset(settings, "Assets/Resources/" + SETTINGS_NAME + ".asset");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log("Successfuly created new settings file.");
} else
{
}
}
#endif
MainSettings = settings;
if (MainSettings == null)
{
settings = Resources.Load<LSFSettings>(DEFAULT_SETTINGS_NAME);
Debug.Log("No settings found. Loading default settings.");
}
}
public static LSFSettings GetSettings()
{
if (MainSettings == null)
Initialize ();
return MainSettings;
}
}
}``` |
3e9b4a2e-fc22-41f8-a134-87fd739ae106 | {
"language": "C#"
} | ```c#
namespace Gu.Roslyn.Asserts.Tests.Net472WithAttributes
{
using Gu.Roslyn.Asserts.Tests.Net472WithAttributes.AnalyzersAndFixes;
using NUnit.Framework;
public partial class RoslynAssertTests
{
[Test]
public void ResetMetadataReferences()
{
CollectionAssert.IsNotEmpty(RoslynAssert.MetadataReferences);
RoslynAssert.MetadataReferences.Clear();
CollectionAssert.IsEmpty(RoslynAssert.MetadataReferences);
RoslynAssert.ResetMetadataReferences();
CollectionAssert.IsNotEmpty(RoslynAssert.MetadataReferences);
}
[Test]
public void CodeFixSingleClassOneErrorCorrectFix()
{
var before = @"
namespace RoslynSandbox
{
class Foo
{
private readonly int ↓_value;
}
}";
var after = @"
namespace RoslynSandbox
{
class Foo
{
private readonly int value;
}
}";
var analyzer = new FieldNameMustNotBeginWithUnderscore();
var fix = new DontUseUnderscoreCodeFixProvider();
RoslynAssert.CodeFix(analyzer, fix, before, after);
}
}
}
```
Rename types in test code. | ```c#
namespace Gu.Roslyn.Asserts.Tests.Net472WithAttributes
{
using Gu.Roslyn.Asserts.Tests.Net472WithAttributes.AnalyzersAndFixes;
using NUnit.Framework;
public partial class RoslynAssertTests
{
[Test]
public void ResetMetadataReferences()
{
CollectionAssert.IsNotEmpty(RoslynAssert.MetadataReferences);
RoslynAssert.MetadataReferences.Clear();
CollectionAssert.IsEmpty(RoslynAssert.MetadataReferences);
RoslynAssert.ResetMetadataReferences();
CollectionAssert.IsNotEmpty(RoslynAssert.MetadataReferences);
}
[Test]
public void CodeFixSingleClassOneErrorCorrectFix()
{
var before = @"
namespace RoslynSandbox
{
class C
{
private readonly int ↓_value;
}
}";
var after = @"
namespace RoslynSandbox
{
class C
{
private readonly int value;
}
}";
var analyzer = new FieldNameMustNotBeginWithUnderscore();
var fix = new DontUseUnderscoreCodeFixProvider();
RoslynAssert.CodeFix(analyzer, fix, before, after);
}
}
}
``` |
fb256eb3-3774-48ba-ac0d-d4067b54f89c | {
"language": "C#"
} | ```c#
using LmpClient.Localization;
using LmpClient.Systems.Chat;
using UnityEngine;
namespace LmpClient.Windows.Chat
{
public partial class ChatWindow
{
private static string _chatInputText = string.Empty;
protected override void DrawWindowContent(int windowId)
{
var pressedEnter = Event.current.type == EventType.KeyDown && !Event.current.shift && Event.current.character == '\n';
GUILayout.BeginVertical();
GUI.DragWindow(MoveRect);
DrawChatMessageBox();
DrawTextInput(pressedEnter);
GUILayout.Space(5);
GUILayout.EndVertical();
}
private static void DrawChatMessageBox()
{
GUILayout.BeginHorizontal();
_chatScrollPos = GUILayout.BeginScrollView(_chatScrollPos);
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
foreach (var channelMessage in ChatSystem.Singleton.ChatMessages)
GUILayout.Label(channelMessage);
GUILayout.EndVertical();
GUILayout.EndScrollView();
GUILayout.EndHorizontal();
}
private static void DrawTextInput(bool pressedEnter)
{
GUILayout.BeginHorizontal();
_chatInputText = GUILayout.TextArea(_chatInputText);
if (pressedEnter || GUILayout.Button(LocalizationContainer.ChatWindowText.Send, GUILayout.Width(WindowWidth * .25f)))
{
if (!string.IsNullOrEmpty(_chatInputText))
{
ChatSystem.Singleton.MessageSender.SendChatMsg(_chatInputText.Trim('\n'));
}
_chatInputText = string.Empty;
}
GUILayout.EndHorizontal();
}
}
}```
Make the chat input only update when enter is not pressed | ```c#
using LmpClient.Localization;
using LmpClient.Systems.Chat;
using UnityEngine;
namespace LmpClient.Windows.Chat
{
public partial class ChatWindow
{
private static string _chatInputText = string.Empty;
protected override void DrawWindowContent(int windowId)
{
var pressedEnter = Event.current.type == EventType.KeyDown && !Event.current.shift && Event.current.character == '\n';
GUILayout.BeginVertical();
GUI.DragWindow(MoveRect);
DrawChatMessageBox();
DrawTextInput(pressedEnter);
GUILayout.Space(5);
GUILayout.EndVertical();
}
private static void DrawChatMessageBox()
{
GUILayout.BeginHorizontal();
_chatScrollPos = GUILayout.BeginScrollView(_chatScrollPos);
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
foreach (var channelMessage in ChatSystem.Singleton.ChatMessages)
GUILayout.Label(channelMessage);
GUILayout.EndVertical();
GUILayout.EndScrollView();
GUILayout.EndHorizontal();
}
private static void DrawTextInput(bool pressedEnter)
{
GUILayout.BeginHorizontal();
if (pressedEnter || GUILayout.Button(LocalizationContainer.ChatWindowText.Send, GUILayout.Width(WindowWidth * .25f)))
{
if (!string.IsNullOrEmpty(_chatInputText))
{
ChatSystem.Singleton.MessageSender.SendChatMsg(_chatInputText.Trim('\n'));
}
_chatInputText = string.Empty;
}
else
{
_chatInputText = GUILayout.TextArea(_chatInputText);
}
GUILayout.EndHorizontal();
}
}
}``` |
21147e2e-b18d-4b7a-9f26-e379301bb9fd | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
using UnityEditor;
using OneDayGame;
namespace DisableAfterTimeEx {
[CustomEditor(typeof (DisableAfterTime))]
public class DisableAfterTimeEditor : Editor {
private SerializedProperty targetGO;
private SerializedProperty delay;
private void OnEnable() {
targetGO = serializedObject.FindProperty("targetGO");
delay = serializedObject.FindProperty("delay");
}
public override void OnInspectorGUI() {
serializedObject.Update();
EditorGUILayout.PropertyField(targetGO);
EditorGUILayout.PropertyField(delay);
serializedObject.ApplyModifiedProperties();
}
}
}
```
Add tooltips and extract inspector classes | ```c#
using UnityEngine;
using System.Collections;
using UnityEditor;
using OneDayGame;
namespace DisableAfterTimeEx {
[CustomEditor(typeof (DisableAfterTime))]
public class DisableAfterTimeEditor : Editor {
private SerializedProperty targetGO;
private SerializedProperty delay;
private void OnEnable() {
targetGO = serializedObject.FindProperty("targetGO");
delay = serializedObject.FindProperty("delay");
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawTargetGOField();
DrawDelayField();
serializedObject.ApplyModifiedProperties();
}
private void DrawDelayField() {
EditorGUILayout.PropertyField(
delay,
new GUIContent(
"Delay",
"Delay before disabling target game object."));
}
private void DrawTargetGOField() {
EditorGUILayout.PropertyField(
targetGO,
new GUIContent(
"Target",
"Game object to be disabled."));
}
}
}
``` |
e29bd313-8640-413d-b734-c86498ac15a6 | {
"language": "C#"
} | ```c#
using NLog;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System;
namespace SyncTrayzor.Syncthing.ApiClient
{
public class SyncthingHttpClientHandler : WebRequestHandler
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public SyncthingHttpClientHandler()
{
// We expect Syncthing to return invalid certs
this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
// We're getting null bodies from somewhere: try and figure out where
var responseString = await response.Content.ReadAsStringAsync();
if (String.IsNullOrWhiteSpace(responseString))
logger.Warn($"Null response received from {request.RequestUri}. {response}. Content (again): {response.Content.ReadAsStringAsync()}");
if (response.IsSuccessStatusCode)
logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim());
else
logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim());
return response;
}
}
}
```
Remove code which logs empty responses | ```c#
using NLog;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System;
namespace SyncTrayzor.Syncthing.ApiClient
{
public class SyncthingHttpClientHandler : WebRequestHandler
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public SyncthingHttpClientHandler()
{
// We expect Syncthing to return invalid certs
this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (response.IsSuccessStatusCode)
logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim());
else
logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim());
return response;
}
}
}
``` |
3a77327e-6e4c-42f1-9d3c-aa3b4f18f2c4 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using EasyHook;
namespace LxRunOffline
{
class Program
{
static void Main(string[] args)
{
int pId = 0;
try
{
RemoteHooking.CreateAndInject(@"C:\Windows\System32\LxRun.exe", string.Join(" ", args), 0, "LxRunHook.dll", "LxRunHook.dll", out pId);
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Error: Failed to launch LxRun.");
Console.WriteLine(e);
Environment.Exit(-1);
}
var process = Process.GetProcessById(pId);
process.WaitForExit();
}
}
}
```
Reset console color on exit. | ```c#
using System;
using System.Diagnostics;
using EasyHook;
namespace LxRunOffline
{
class Program
{
static void Main(string[] args)
{
int pId = 0;
try
{
RemoteHooking.CreateAndInject(@"C:\Windows\System32\LxRun.exe", string.Join(" ", args), 0, "LxRunHook.dll", "LxRunHook.dll", out pId);
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Error: Failed to launch LxRun.");
Console.WriteLine(e);
Console.ResetColor();
Environment.Exit(-1);
}
var process = Process.GetProcessById(pId);
process.WaitForExit();
}
}
}
``` |
1df29875-c351-4234-b967-183e1741a1bf | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace QuickFont {
public sealed class QFontGlyph {
/// <summary>
/// Which texture page the glyph is on
/// </summary>
public int Page {
get;
private set;
}
/// <summary>
/// The rectangle defining the glyphs position on the page
/// </summary>
public Rectangle Rect {
get;
set;
}
/// <summary>
/// How far the glyph would need to be vertically offset to be vertically in line with the tallest glyph in the set of all glyphs
/// </summary>
public int YOffset {
get;
set;
}
/// <summary>
/// Which character this glyph represents
/// </summary>
public char Character {
get;
private set;
}
public QFontGlyph (int page, Rectangle rect, int yOffset, char character) {
Page = page;
Rect = rect;
YOffset = yOffset;
Character = character;
}
}
}
```
Allow suppression of colour for specific glyphs. | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace QuickFont {
public sealed class QFontGlyph {
/// <summary>
/// Which texture page the glyph is on
/// </summary>
public int Page {
get;
private set;
}
/// <summary>
/// The rectangle defining the glyphs position on the page
/// </summary>
public Rectangle Rect {
get;
set;
}
/// <summary>
/// How far the glyph would need to be vertically offset to be vertically in line with the tallest glyph in the set of all glyphs
/// </summary>
public int YOffset {
get;
set;
}
/// <summary>
/// Which character this glyph represents
/// </summary>
public char Character {
get;
private set;
}
/// <summary>
/// Indicates whether colouring should be suppressed for this glyph.
/// </summary>
/// <value><c>true</c> if suppress colouring; otherwise, <c>false</c>.</value>
public bool SuppressColouring {
get;
set;
}
public QFontGlyph (int page, Rectangle rect, int yOffset, char character) {
Page = page;
Rect = rect;
YOffset = yOffset;
Character = character;
}
}
}
``` |
a4979984-41de-4dab-9ebc-e83cb3887582 | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using Rhino.ServiceBus.Config;
using Rhino.ServiceBus.Impl;
namespace Rhino.ServiceBus.Hosting
{
public abstract class AbstractBootStrapper : IDisposable
{
private AbstractRhinoServiceBusConfiguration config;
public virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public virtual void AfterStart()
{
}
public virtual void InitializeContainer()
{
CreateContainer();
config = CreateConfiguration();
ConfigureBusFacility(config);
config.Configure();
}
public virtual void UseConfiguration(BusConfigurationSection configurationSection)
{
config.UseConfiguration(configurationSection);
}
public abstract void CreateContainer();
public abstract void ExecuteDeploymentActions(string user);
public abstract void ExecuteEnvironmentValidationActions();
public abstract T GetInstance<T>();
protected virtual bool IsTypeAcceptableForThisBootStrapper(Type t)
{
return true;
}
protected virtual AbstractRhinoServiceBusConfiguration CreateConfiguration()
{
return new RhinoServiceBusConfiguration();
}
protected virtual void ConfigureBusFacility(AbstractRhinoServiceBusConfiguration configuration)
{
}
public virtual void BeforeStart()
{
}
public abstract void Dispose();
}
}```
Move config.Configure to BeforeStart which gives the overloads the chance to change it before it throw because it dose not found an configuration. | ```c#
using System;
using System.Reflection;
using Rhino.ServiceBus.Config;
using Rhino.ServiceBus.Impl;
namespace Rhino.ServiceBus.Hosting
{
public abstract class AbstractBootStrapper : IDisposable
{
private AbstractRhinoServiceBusConfiguration config;
public virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public virtual void InitializeContainer()
{
CreateContainer();
config = CreateConfiguration();
ConfigureBusFacility(config);
}
public virtual void UseConfiguration(BusConfigurationSection configurationSection)
{
config.UseConfiguration(configurationSection);
}
public abstract void CreateContainer();
public abstract void ExecuteDeploymentActions(string user);
public abstract void ExecuteEnvironmentValidationActions();
public abstract T GetInstance<T>();
protected virtual bool IsTypeAcceptableForThisBootStrapper(Type t)
{
return true;
}
protected virtual AbstractRhinoServiceBusConfiguration CreateConfiguration()
{
return new RhinoServiceBusConfiguration();
}
protected virtual void ConfigureBusFacility(AbstractRhinoServiceBusConfiguration configuration)
{
}
public virtual void BeforeStart()
{
config.Configure();
}
public virtual void AfterStart()
{
}
public abstract void Dispose();
}
}``` |
23387d80-b87a-4d0f-a36c-8119ad375bdc | {
"language": "C#"
} | ```c#
using Bloom.Api;
using Bloom.Book;
using Bloom.Collection;
using NUnit.Framework;
namespace BloomTests.web
{
[TestFixture]
public class ReadersApiTests
{
private EnhancedImageServer _server;
[SetUp]
public void Setup()
{
var bookSelection = new BookSelection();
bookSelection.SelectBook(new Bloom.Book.Book());
_server = new EnhancedImageServer(bookSelection);
//needed to avoid a check in the server
_server.CurrentCollectionSettings = new CollectionSettings();
var controller = new ReadersApi(bookSelection);
controller.RegisterWithServer(_server);
}
[TearDown]
public void TearDown()
{
_server.Dispose();
_server = null;
}
[Test]
public void IsReceivingApiCalls()
{
var result = ApiTest.GetString(_server,"readers/test");
Assert.That(result, Is.EqualTo("OK"));
}
}
}```
Fix url of api test | ```c#
using Bloom.Api;
using Bloom.Book;
using Bloom.Collection;
using NUnit.Framework;
namespace BloomTests.web
{
[TestFixture]
public class ReadersApiTests
{
private EnhancedImageServer _server;
[SetUp]
public void Setup()
{
var bookSelection = new BookSelection();
bookSelection.SelectBook(new Bloom.Book.Book());
_server = new EnhancedImageServer(bookSelection);
//needed to avoid a check in the server
_server.CurrentCollectionSettings = new CollectionSettings();
var controller = new ReadersApi(bookSelection);
controller.RegisterWithServer(_server);
}
[TearDown]
public void TearDown()
{
_server.Dispose();
_server = null;
}
[Test]
public void IsReceivingApiCalls()
{
var result = ApiTest.GetString(_server,"readers/io/test");
Assert.That(result, Is.EqualTo("OK"));
}
}
}``` |
0f5c0d29-53f8-47bb-ade4-b477276312ec | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Rulesets.Catch.Objects;
using osuTK;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints.Components
{
public class PlacementEditablePath : EditablePath
{
private JuiceStreamPathVertex originalNewVertex;
public PlacementEditablePath(Func<float, double> positionToDistance)
: base(positionToDistance)
{
}
public void AddNewVertex()
{
var endVertex = Vertices[^1];
int index = AddVertex(endVertex.Distance, endVertex.X);
for (int i = 0; i < VertexCount; i++)
{
VertexStates[i].IsSelected = i == index;
VertexStates[i].VertexBeforeChange = Vertices[i];
}
originalNewVertex = Vertices[index];
}
/// <summary>
/// Move the vertex added by <see cref="AddNewVertex"/> in the last time.
/// </summary>
public void MoveLastVertex(Vector2 screenSpacePosition)
{
Vector2 position = ToRelativePosition(screenSpacePosition);
double distanceDelta = PositionToDistance(position.Y) - originalNewVertex.Distance;
float xDelta = position.X - originalNewVertex.X;
MoveSelectedVertices(distanceDelta, xDelta);
}
}
}
```
Use the more consistent `lastVertex`, with a comment | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Rulesets.Catch.Objects;
using osuTK;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints.Components
{
public class PlacementEditablePath : EditablePath
{
/// <summary>
/// The original position of the last added vertex.
/// This is not same as the last vertex of the current path because the vertex ordering can change.
/// </summary>
private JuiceStreamPathVertex lastVertex;
public PlacementEditablePath(Func<float, double> positionToDistance)
: base(positionToDistance)
{
}
public void AddNewVertex()
{
var endVertex = Vertices[^1];
int index = AddVertex(endVertex.Distance, endVertex.X);
for (int i = 0; i < VertexCount; i++)
{
VertexStates[i].IsSelected = i == index;
VertexStates[i].VertexBeforeChange = Vertices[i];
}
lastVertex = Vertices[index];
}
/// <summary>
/// Move the vertex added by <see cref="AddNewVertex"/> in the last time.
/// </summary>
public void MoveLastVertex(Vector2 screenSpacePosition)
{
Vector2 position = ToRelativePosition(screenSpacePosition);
double distanceDelta = PositionToDistance(position.Y) - lastVertex.Distance;
float xDelta = position.X - lastVertex.X;
MoveSelectedVertices(distanceDelta, xDelta);
}
}
}
``` |
34309e40-c850-492c-afc2-69f595d2d3bf | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
namespace osu.Game.Online.Rooms
{
public class JoinRoomRequest : APIRequest
{
public readonly Room Room;
public readonly string Password;
public JoinRoomRequest(Room room, string password)
{
Room = room;
Password = password;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
return req;
}
// Todo: Password needs to be specified here rather than via AddParameter() because this is a PUT request. May be a framework bug.
protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}?password={Password}";
}
}
```
Fix room password not being percent-encoded in join request | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
namespace osu.Game.Online.Rooms
{
public class JoinRoomRequest : APIRequest
{
public readonly Room Room;
public readonly string Password;
public JoinRoomRequest(Room room, string password)
{
Room = room;
Password = password;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
req.AddParameter(@"password", Password, RequestParameterType.Query);
return req;
}
protected override string Target => $@"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
``` |
68b86d84-16d1-40a7-9aae-f454cc6155da | {
"language": "C#"
} | ```c#
using System.ComponentModel.Composition;
namespace Flood.Editor.Controls
{
class ToolClose : EditorTool, BarTool
{
[Import]
DocumentManager docManager;
public void OnSelect()
{
if (docManager.Current != null)
docManager.Close(docManager.Current.Id);
}
public string Text
{
get { return "Close"; }
}
public string Image
{
get { return "close.png"; }
}
}
}
```
Disable document selection by id. | ```c#
using System.ComponentModel.Composition;
namespace Flood.Editor.Controls
{
class ToolClose : EditorTool, BarTool
{
[Import]
DocumentManager docManager;
public void OnSelect()
{
//if (docManager.Current != null)
// docManager.Close(docManager.Current.Id);
}
public string Text
{
get { return "Close"; }
}
public string Image
{
get { return "close.png"; }
}
}
}
``` |
19db1a13-959c-443a-ada1-95a4c8c0f89f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GitDataExplorer.Results.Commits;
namespace GitDataExplorer.Results
{
class ListSimpleCommitsResult : IResult
{
public ExecutionResult ExecutionResult { get; private set; }
public IList<SimpleCommitResult> Commits { get; } = new List<SimpleCommitResult>();
public void ParseResult(IList<string> lines)
{
var tmpList = new List<string>();
foreach (var line in lines)
{
if (line.StartsWith("A") || line.StartsWith("M") || line.StartsWith("R"))
{
tmpList.Add(line);
}
else
{
if (tmpList.Count > 0)
{
var result = new SimpleCommitResult();
result.ParseResult(tmpList);
Commits.Add(result);
}
tmpList.Clear();
tmpList.Add(line);
}
}
if (tmpList.Count > 0)
{
var result = new SimpleCommitResult();
result.ParseResult(tmpList);
Commits.Add(result);
}
}
}
}
```
Add deleted and copied to the parsed statuses | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GitDataExplorer.Results.Commits;
namespace GitDataExplorer.Results
{
class ListSimpleCommitsResult : IResult
{
private char[] statusLetters = { 'M', 'A', 'R', 'C', 'D' };
public ExecutionResult ExecutionResult { get; private set; }
public IList<SimpleCommitResult> Commits { get; } = new List<SimpleCommitResult>();
public void ParseResult(IList<string> lines)
{
var tmpList = new List<string>();
foreach (var line in lines)
{
if (Array.IndexOf(statusLetters, line[0]) >= 0)
{
tmpList.Add(line);
}
else
{
if (tmpList.Count > 0)
{
var result = new SimpleCommitResult();
result.ParseResult(tmpList);
Commits.Add(result);
}
tmpList.Clear();
tmpList.Add(line);
}
}
if (tmpList.Count > 0)
{
var result = new SimpleCommitResult();
result.ParseResult(tmpList);
Commits.Add(result);
}
}
}
}
``` |
6c80fcb2-8eb3-4773-a6b1-ddc0749138f3 | {
"language": "C#"
} | ```c#
namespace Nilgiri.Examples
{
using Xunit;
using Nilgiri.Tests.Common;
using static Nilgiri.ShouldStyle;
public partial class ExampleOf_Should
{
public class Not_Be_Ok
{
[Fact]
public void Int32()
{
_(0).Should.Not.Be.Ok();
_(() => 0).Should.Not.Be.Ok();
}
[Fact]
public void Nullable()
{
_((bool?)false).Should.Not.Be.Ok();
_(() => (bool?)false).Should.Not.Be.Ok();
}
[Fact]
public void String()
{
_((string)null).Should.Not.Be.Ok();
_(() => (string)null).Should.Not.Be.Ok();
_(System.String.Empty).Should.Not.Be.Ok();
_(() => System.String.Empty).Should.Not.Be.Ok();
_("").Should.Not.Be.Ok();
_(() => "").Should.Not.Be.Ok();
_(" ").Should.Not.Be.Ok();
_(() => " ").Should.Not.Be.Ok();
}
[Fact]
public void ReferenceTypes()
{
_((StubClass)null).Should.Not.Be.Ok();
_(() => (StubClass)null).Should.Not.Be.Ok();
}
}
}
}
```
Add missing Nullable example | ```c#
namespace Nilgiri.Examples
{
using Xunit;
using Nilgiri.Tests.Common;
using static Nilgiri.ShouldStyle;
public partial class ExampleOf_Should
{
public class Not_Be_Ok
{
[Fact]
public void Int32()
{
_(0).Should.Not.Be.Ok();
_(() => 0).Should.Not.Be.Ok();
}
[Fact]
public void Nullable()
{
_((bool?)false).Should.Not.Be.Ok();
_(() => (bool?)false).Should.Not.Be.Ok();
_((bool?)null).Should.Not.Be.Ok();
_(() => (bool?)null).Should.Not.Be.Ok();
}
[Fact]
public void String()
{
_((string)null).Should.Not.Be.Ok();
_(() => (string)null).Should.Not.Be.Ok();
_(System.String.Empty).Should.Not.Be.Ok();
_(() => System.String.Empty).Should.Not.Be.Ok();
_("").Should.Not.Be.Ok();
_(() => "").Should.Not.Be.Ok();
_(" ").Should.Not.Be.Ok();
_(() => " ").Should.Not.Be.Ok();
}
[Fact]
public void ReferenceTypes()
{
_((StubClass)null).Should.Not.Be.Ok();
_(() => (StubClass)null).Should.Not.Be.Ok();
}
}
}
}
``` |
c50edfb8-2117-4805-a055-5b8e4d7579a7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nop.Plugin.Api.Constants
{
public static class WebHookNames
{
public const string FiltersGetAction = "FiltersGetAction";
public const string GetWebhookByIdAction = "GetWebHookByIdAction";
public const string CustomerCreated = "customer/created";
public const string CustomerUpdated = "customer/updated";
public const string CustomerDeleted = "customer/deleted";
public const string ProductCreated = "product/created";
public const string ProductUpdated = "product/updated";
public const string ProductDeleted = "product/deleted";
public const string CategoryCreated = "category/created";
public const string CategoryUpdated = "category/updated";
public const string CategoryDeleted = "category/deleted";
public const string OrderCreated = "order/created";
public const string OrderUpdated = "order/updated";
public const string OrderDeleted = "order/deleted";
}
}
```
Change the web hook names | ```c#
namespace Nop.Plugin.Api.Constants
{
public static class WebHookNames
{
public const string FiltersGetAction = "FiltersGetAction";
public const string GetWebhookByIdAction = "GetWebHookByIdAction";
public const string CustomerCreated = "customers/created";
public const string CustomerUpdated = "customers/updated";
public const string CustomerDeleted = "customers/deleted";
public const string ProductCreated = "products/created";
public const string ProductUpdated = "products/updated";
public const string ProductDeleted = "products/deleted";
public const string CategoryCreated = "categories/created";
public const string CategoryUpdated = "categories/updated";
public const string CategoryDeleted = "categories/deleted";
public const string OrderCreated = "orders/created";
public const string OrderUpdated = "orders/updated";
public const string OrderDeleted = "orders/deleted";
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.