doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
0c133d89-572b-4cc2-a750-f56dc6416454 | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
```
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning. | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
``` |
1ecb925f-2b73-4742-981e-2ad9796a8193 | {
"language": "C#"
} | ```c#
using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
// char key = Console.ReadKey(true).KeyChar;
// var game = new Game("HANG THE MAN");
// bool wasCorrect = game.GuessLetter(key);
// Console.WriteLine(wasCorrect.ToString());
// var output = game.ShownWord();
// Console.WriteLine(output);
var table = new Table(
Console.WindowWidth, // width
2 // spacing
);
var output = table.Draw();
Console.WriteLine(output);
}
}
}
```
Change indent to 2 spaces | ```c#
using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
// char key = Console.ReadKey(true).KeyChar;
// var game = new Game("HANG THE MAN");
// bool wasCorrect = game.GuessLetter(key);
// Console.WriteLine(wasCorrect.ToString());
// var output = game.ShownWord();
// Console.WriteLine(output);
var table = new Table(
Console.WindowWidth, // width
2 // spacing
);
var output = table.Draw();
Console.WriteLine(output);
}
}
}
``` |
b2d7ade0-c1ef-41fc-9cf7-fc67f16eacc1 | {
"language": "C#"
} | ```c#
using Peasy;
using Peasy.Core;
using Orders.com.BLL.DataProxy;
namespace Orders.com.BLL.Services
{
public abstract class OrdersDotComServiceBase<T> : BusinessServiceBase<T, long> where T : IDomainObject<long>, new()
{
public OrdersDotComServiceBase(IOrdersDotComDataProxy<T> dataProxy) : base(dataProxy)
{
}
}
}
```
Add conditional business rule execution based on successful validation rule execution | ```c#
using Peasy;
using Peasy.Core;
using Orders.com.BLL.DataProxy;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Orders.com.BLL.Services
{
public abstract class OrdersDotComServiceBase<T> : BusinessServiceBase<T, long> where T : IDomainObject<long>, new()
{
public OrdersDotComServiceBase(IOrdersDotComDataProxy<T> dataProxy) : base(dataProxy)
{
}
protected override IEnumerable<ValidationResult> GetAllErrorsForInsert(T entity, ExecutionContext<T> context)
{
var validationErrors = GetValidationResultsForInsert(entity, context);
if (!validationErrors.Any())
{
var businessRuleErrors = GetBusinessRulesForInsert(entity, context).GetValidationResults();
validationErrors.Concat(businessRuleErrors);
}
return validationErrors;
}
protected override async Task<IEnumerable<ValidationResult>> GetAllErrorsForInsertAsync(T entity, ExecutionContext<T> context)
{
var validationErrors = GetValidationResultsForInsert(entity, context);
if (!validationErrors.Any())
{
var businessRuleErrors = await GetBusinessRulesForInsertAsync(entity, context);
validationErrors.Concat(await businessRuleErrors.GetValidationResultsAsync());
}
return validationErrors;
}
protected override IEnumerable<ValidationResult> GetAllErrorsForUpdate(T entity, ExecutionContext<T> context)
{
var validationErrors = GetValidationResultsForUpdate(entity, context);
if (!validationErrors.Any())
{
var businessRuleErrors = GetBusinessRulesForUpdate(entity, context).GetValidationResults();
validationErrors.Concat(businessRuleErrors);
}
return validationErrors;
}
protected override async Task<IEnumerable<ValidationResult>> GetAllErrorsForUpdateAsync(T entity, ExecutionContext<T> context)
{
var validationErrors = GetValidationResultsForUpdate(entity, context);
if (!validationErrors.Any())
{
var businessRuleErrors = await GetBusinessRulesForUpdateAsync(entity, context);
validationErrors.Concat(await businessRuleErrors.GetValidationResultsAsync());
}
return validationErrors;
}
}
}
``` |
bff35b55-46f0-4002-8e55-d51058e0e29e | {
"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.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.DotNet.Archive;
namespace RepoTasks
{
public class CreateLzma : Task
{
[Required]
public string OutputPath { get; set; }
[Required]
public string[] Sources { get; set; }
public override bool Execute()
{
var progress = new ConsoleProgressReport();
using (var archive = new IndexedArchive())
{
foreach (var source in Sources)
{
if (Directory.Exists(source))
{
Log.LogMessage(MessageImportance.High, $"Adding directory: {source}");
archive.AddDirectory(source, progress);
}
else
{
Log.LogMessage(MessageImportance.High, $"Adding file: {source}");
archive.AddFile(source, Path.GetFileName(source));
}
}
archive.Save(OutputPath, progress);
}
return true;
}
}
}
```
Remove trailing slashes when creating LZMAs | ```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.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.DotNet.Archive;
namespace RepoTasks
{
public class CreateLzma : Task
{
[Required]
public string OutputPath { get; set; }
[Required]
public string[] Sources { get; set; }
public override bool Execute()
{
var progress = new ConsoleProgressReport();
using (var archive = new IndexedArchive())
{
foreach (var source in Sources)
{
if (Directory.Exists(source))
{
var trimmedSource = source.TrimEnd(new []{ '\\', '/' });
Log.LogMessage(MessageImportance.High, $"Adding directory: {trimmedSource}");
archive.AddDirectory(trimmedSource, progress);
}
else
{
Log.LogMessage(MessageImportance.High, $"Adding file: {source}");
archive.AddFile(source, Path.GetFileName(source));
}
}
archive.Save(OutputPath, progress);
}
return true;
}
}
}
``` |
4c1a03f0-223f-4334-9ff8-3a19273e73ba | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.IO;
namespace HolzShots.IO
{
public static class HolzShotsPaths
{
private static readonly string SystemAppDataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
private static readonly string UserPicturesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
private static readonly string AppDataDirectory = Path.Combine(SystemAppDataDirectory, LibraryInformation.Name);
public static string SystemPath { get; } = Environment.GetFolderPath(Environment.SpecialFolder.System);
public static string PluginDirectory { get; } = Path.Combine(AppDataDirectory, "Plugin");
public static string CustomUploadersDirectory { get; } = Path.Combine(AppDataDirectory, "CustomUploaders");
public static string UserSettingsFilePath { get; } = Path.Combine(AppDataDirectory, "settings.json");
public static string DefaultScreenshotSavePath { get; } = Path.Combine(UserPicturesDirectory, LibraryInformation.Name);
/// <summary>
/// We are doing this synchronously, assuming the application is not located on a network drive.
/// See: https://stackoverflow.com/a/20596865
/// </summary>
/// <exception cref="System.UnauthorizedAccessException" />
/// <exception cref="System.IO.PathTooLongException" />
public static void EnsureDirectory(string directory)
{
Debug.Assert(directory != null);
DirectoryEx.EnsureDirectory(directory);
}
}
}
```
Put custom uploaders in same dir as other plugins | ```c#
using System;
using System.Diagnostics;
using System.IO;
namespace HolzShots.IO
{
public static class HolzShotsPaths
{
private static readonly string SystemAppDataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
private static readonly string UserPicturesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
private static readonly string AppDataDirectory = Path.Combine(SystemAppDataDirectory, LibraryInformation.Name);
public static string SystemPath { get; } = Environment.GetFolderPath(Environment.SpecialFolder.System);
public static string PluginDirectory { get; } = Path.Combine(AppDataDirectory, "Plugin");
public static string CustomUploadersDirectory { get; } = PluginDirectory;
public static string UserSettingsFilePath { get; } = Path.Combine(AppDataDirectory, "settings.json");
public static string DefaultScreenshotSavePath { get; } = Path.Combine(UserPicturesDirectory, LibraryInformation.Name);
/// <summary>
/// We are doing this synchronously, assuming the application is not located on a network drive.
/// See: https://stackoverflow.com/a/20596865
/// </summary>
/// <exception cref="System.UnauthorizedAccessException" />
/// <exception cref="System.IO.PathTooLongException" />
public static void EnsureDirectory(string directory)
{
Debug.Assert(directory != null);
DirectoryEx.EnsureDirectory(directory);
}
}
}
``` |
b19affb0-dfea-42c2-8697-89b8f5d4d051 | {
"language": "C#"
} | ```c#
namespace Nancy.Extensions
{
using System;
using System.Linq;
/// <summary>
/// Containing extensions for the <see cref="Request"/> object
/// </summary>
public static class RequestExtensions
{
/// <summary>
/// An extension method making it easy to check if the reqeuest was done using ajax
/// </summary>
/// <param name="request">The request made by client</param>
/// <returns><see langword="true" /> if the request was done using ajax, otherwise <see langword="false"/>.</returns>
public static bool IsAjaxRequest(this Request request)
{
const string ajaxRequestHeaderKey = "X-Requested-With";
const string ajaxRequestHeaderValue = "XMLHttpRequest";
return request.Headers[ajaxRequestHeaderKey].Contains(ajaxRequestHeaderValue);
}
/// <summary>
/// Gets a value indicating whether the request is local.
/// </summary>
/// <param name="request">The request made by client</param>
/// <returns><see langword="true" /> if the request is local, otherwise <see langword="false"/>.</returns>
public static bool IsLocal(this Request request)
{
if (string.IsNullOrEmpty(request.UserHostAddress) || string.IsNullOrEmpty(request.Url))
{
return false;
}
try
{
var uri = new Uri(request.Url);
return uri.IsLoopback;
}
catch (Exception)
{
// Invalid Request.Url string
return false;
}
}
}
}
```
Check isLocal using Uri.TryCreate. It is possible in case we have only absolute url. | ```c#
namespace Nancy.Extensions
{
using System;
using System.Linq;
/// <summary>
/// Containing extensions for the <see cref="Request"/> object
/// </summary>
public static class RequestExtensions
{
/// <summary>
/// An extension method making it easy to check if the reqeuest was done using ajax
/// </summary>
/// <param name="request">The request made by client</param>
/// <returns><see langword="true" /> if the request was done using ajax, otherwise <see langword="false"/>.</returns>
public static bool IsAjaxRequest(this Request request)
{
const string ajaxRequestHeaderKey = "X-Requested-With";
const string ajaxRequestHeaderValue = "XMLHttpRequest";
return request.Headers[ajaxRequestHeaderKey].Contains(ajaxRequestHeaderValue);
}
/// <summary>
/// Gets a value indicating whether the request is local.
/// </summary>
/// <param name="request">The request made by client</param>
/// <returns><see langword="true" /> if the request is local, otherwise <see langword="false"/>.</returns>
public static bool IsLocal(this Request request)
{
if (string.IsNullOrEmpty(request.UserHostAddress) || string.IsNullOrEmpty(request.Url))
{
return false;
}
Uri uri = null;
if (Uri.TryCreate(request.Url, UriKind.Absolute, out uri))
{
return uri.IsLoopback;
}
else
{
// Invalid or relative Request.Url string
return false;
}
}
}
}
``` |
e29cde0b-cb81-4dfd-aeab-4a2fde68e703 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Refit.Generator
{
class Program
{
static void Main(string[] args)
{
var generator = new InterfaceStubGenerator();
var target = new FileInfo(args[0]);
var files = args[1].Split(';').Select(x => new FileInfo(x)).ToArray();
var template = generator.GenerateInterfaceStubs(files.Select(x => x.FullName).ToArray());
File.WriteAllText(target.FullName, template);
}
}
}
```
Fix a dumb bug in the interface generator | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Refit.Generator
{
class Program
{
static void Main(string[] args)
{
// NB: @Compile passes us a list of files relative to the project
// directory - we're going to assume that the target is always in
// the same directory as the project file
var generator = new InterfaceStubGenerator();
var target = new FileInfo(args[0]);
var targetDir = target.DirectoryName;
var files = args[1].Split(';')
.Select(x => new FileInfo(Path.Combine(targetDir, x)))
.ToArray();
var template = generator.GenerateInterfaceStubs(files.Select(x => x.FullName).ToArray());
File.WriteAllText(target.FullName, template);
}
}
}
``` |
72ac3d5a-1448-49b6-809c-45d5226668db | {
"language": "C#"
} | ```c#
using System.Globalization;
using Abp.Configuration.Startup;
using Abp.Extensions;
using Abp.Logging;
namespace Abp.Localization
{
public static class LocalizationSourceHelper
{
public static string ReturnGivenNameOrThrowException(ILocalizationConfiguration configuration, string sourceName, string name, CultureInfo culture)
{
var exceptionMessage = $"Can not find '{name}' in localization source '{sourceName}'!";
if (!configuration.ReturnGivenTextIfNotFound)
{
throw new AbpException(exceptionMessage);
}
LogHelper.Logger.Warn(exceptionMessage);
#if NET46
var notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase(culture)
: name;
#else
var notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase() //TODO: Removed culture since it's not supported by netstandard
: name;
#endif
return configuration.WrapGivenTextIfNotFound
? $"[{notFoundText}]"
: notFoundText;
}
}
}
```
Implement humanize test localization for current culture. | ```c#
using System.Globalization;
using Abp.Configuration.Startup;
using Abp.Extensions;
using Abp.Logging;
namespace Abp.Localization
{
public static class LocalizationSourceHelper
{
public static string ReturnGivenNameOrThrowException(ILocalizationConfiguration configuration, string sourceName, string name, CultureInfo culture)
{
var exceptionMessage = $"Can not find '{name}' in localization source '{sourceName}'!";
if (!configuration.ReturnGivenTextIfNotFound)
{
throw new AbpException(exceptionMessage);
}
LogHelper.Logger.Warn(exceptionMessage);
string notFoundText;
#if NET46
notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase(culture)
: name;
#else
using (CultureInfoHelper.Use(culture))
{
notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase()
: name;
}
#endif
return configuration.WrapGivenTextIfNotFound
? $"[{notFoundText}]"
: notFoundText;
}
}
}
``` |
347e6d3d-a0c3-4a55-8fa8-7ab2a4925928 | {
"language": "C#"
} | ```c#
using System;
using AspNet.WebApi.HtmlMicrodataFormatter;
namespace NuGet.Lucene.Web.Models
{
public class PackageVersionSummary
{
private readonly StrictSemanticVersion version;
private readonly DateTimeOffset lastUpdated;
private readonly int versionDownloadCount;
private readonly Link link;
public StrictSemanticVersion Version
{
get { return version; }
}
public DateTimeOffset LastUpdated
{
get { return lastUpdated; }
}
public int VersionDownloadCount
{
get { return versionDownloadCount; }
}
public Link Link
{
get { return link; }
}
public PackageVersionSummary(LucenePackage package, Link link)
: this(package.Version, package.LastUpdated, package.VersionDownloadCount, link)
{
}
public PackageVersionSummary(StrictSemanticVersion version, DateTimeOffset lastUpdated, int versionDownloadCount, Link link)
{
this.version = version;
this.lastUpdated = lastUpdated;
this.versionDownloadCount = versionDownloadCount;
this.link = link;
}
}
}```
Include id and title on package version history items. | ```c#
using System;
using AspNet.WebApi.HtmlMicrodataFormatter;
namespace NuGet.Lucene.Web.Models
{
public class PackageVersionSummary
{
private readonly string id;
private readonly string title;
private readonly StrictSemanticVersion version;
private readonly DateTimeOffset lastUpdated;
private readonly int versionDownloadCount;
private readonly Link link;
public string Id
{
get { return id; }
}
public string Title
{
get { return title; }
}
public StrictSemanticVersion Version
{
get { return version; }
}
public DateTimeOffset LastUpdated
{
get { return lastUpdated; }
}
public int VersionDownloadCount
{
get { return versionDownloadCount; }
}
public Link Link
{
get { return link; }
}
public PackageVersionSummary(LucenePackage package, Link link)
: this(package.Id, package.Title, package.Version, package.LastUpdated, package.VersionDownloadCount, link)
{
}
public PackageVersionSummary(string id, string title, StrictSemanticVersion version, DateTimeOffset lastUpdated, int versionDownloadCount, Link link)
{
this.id = id;
this.title = title;
this.version = version;
this.lastUpdated = lastUpdated;
this.versionDownloadCount = versionDownloadCount;
this.link = link;
}
}
}``` |
71d1e354-deef-4404-967a-ba3ddf6ca830 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication
{
public partial class CreateNewProduct
{
partial void CreateNewProduct_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)
{
// Write your code here.
this.ProductProperty = new Product();
}
partial void CreateNewProduct_Saved()
{
// Write your code here.
this.Close(false);
Application.Current.ShowDefaultScreen(this.ProductProperty);
}
}
}```
Create private and public key when saving a new product | ```c#
using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication
{
public partial class CreateNewProduct
{
partial void CreateNewProduct_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)
{
// Write your code here.
this.ProductProperty = new Product();
}
partial void CreateNewProduct_Saved()
{
// Write your code here.
this.Close(false);
Application.Current.ShowDefaultScreen(this.ProductProperty);
}
partial void CreateNewProduct_Saving(ref bool handled)
{
if (ProductProperty.KeyPair != null)
return;
ProductProperty.KeyPair = new KeyPair();
if (!string.IsNullOrWhiteSpace(ProductProperty.KeyPair.PrivateKey))
return;
var passPhrase = this.ShowInputBox("Please enter the pass phrase to encrypt the private key.",
"Private Key Generator");
if (string.IsNullOrWhiteSpace(passPhrase))
{
this.ShowMessageBox("Invalid pass phrase!", "Private Key Generator", MessageBoxOption.Ok);
handled = false;
return;
}
var keyPair = Portable.Licensing.Security.Cryptography.KeyGenerator.Create().GenerateKeyPair();
ProductProperty.KeyPair.PrivateKey = keyPair.ToEncryptedPrivateKeyString(passPhrase);
ProductProperty.KeyPair.PublicKey = keyPair.ToPublicKeyString();
}
}
}``` |
f556edbb-1245-4385-8147-68b026461486 | {
"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;
req.AddParameter("password", Password);
return req;
}
protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
```
Fix web request failing if password is null | ```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;
if (!string.IsNullOrEmpty(Password))
req.AddParameter("password", Password);
return req;
}
protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
``` |
1ccb03c0-d9f9-472d-b622-eab8f78a4faf | {
"language": "C#"
} | ```c#
using DynamicData;
using DynamicData.Aggregation;
using ReactiveUI;
using Sakuno.ING.Game.Models;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
namespace Sakuno.ING.ViewModels.Homeport
{
public sealed class FleetViewModel : ReactiveObject, IHomeportTabViewModel
{
public PlayerFleet Model { get; }
public IReadOnlyCollection<ShipViewModel> Ships { get; }
private readonly ObservableAsPropertyHelper<int> _totalLevel;
public int TotalLevel => _totalLevel.Value;
private readonly ObservableAsPropertyHelper<int> _speed;
public ShipSpeed Speed => (ShipSpeed)_speed.Value;
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set => this.RaiseAndSetIfChanged(ref _isSelected, value);
}
public FleetViewModel(PlayerFleet fleet)
{
Model = fleet;
var ships = fleet.Ships.AsObservableChangeSet();
Ships = ships.Transform(r => new ShipViewModel(r)).Bind();
_totalLevel = ships.Sum(r => r.Leveling.Level).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(TotalLevel), deferSubscription: true);
_speed = ships.Minimum(r => (int)r.Speed).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(ShipSpeed));
}
}
}
```
Fix fleet ship list not update | ```c#
using DynamicData;
using DynamicData.Aggregation;
using DynamicData.Binding;
using ReactiveUI;
using Sakuno.ING.Game.Models;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
namespace Sakuno.ING.ViewModels.Homeport
{
public sealed class FleetViewModel : ReactiveObject, IHomeportTabViewModel
{
public PlayerFleet Model { get; }
public IReadOnlyCollection<ShipViewModel> Ships { get; }
private readonly ObservableAsPropertyHelper<int> _totalLevel;
public int TotalLevel => _totalLevel.Value;
private readonly ObservableAsPropertyHelper<int> _speed;
public ShipSpeed Speed => (ShipSpeed)_speed.Value;
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set => this.RaiseAndSetIfChanged(ref _isSelected, value);
}
public FleetViewModel(PlayerFleet fleet)
{
Model = fleet;
var ships = fleet.Ships.ToObservableChangeSet();
Ships = ships.Transform(r => new ShipViewModel(r)).Bind();
_totalLevel = ships.Sum(r => r.Leveling.Level).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(TotalLevel), deferSubscription: true);
_speed = ships.Minimum(r => (int)r.Speed).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(ShipSpeed));
}
}
}
``` |
da30d59d-137d-482e-8c3b-4cb209af3deb | {
"language": "C#"
} | ```c#
@model RedFolder.Podcast.Models.PodcastMetrics
<div class="podcast-metrics">
<div>
<h3 class="title">Number of episodes</h3>
<p class="metric">
@Model.NumberOfEpisodes
</p>
</div>
<div>
<h3 class="title">Total duration</h3>
<p class="metric">
@Model.TotalDuration.Hours Hours, @Model.TotalDuration.Minutes Minutes
</p>
</div>
</div>```
Fix for display of hours | ```c#
@model RedFolder.Podcast.Models.PodcastMetrics
<div class="podcast-metrics">
<div>
<h3 class="title">Number of episodes</h3>
<p class="metric">
@Model.NumberOfEpisodes
</p>
</div>
<div>
<h3 class="title">Total duration</h3>
<p class="metric">
@Model.TotalDuration.TotalHours.ToString("###") Hours, @Model.TotalDuration.Minutes Minutes
</p>
</div>
</div>``` |
8ea6f048-cacf-462d-b28d-c2ccbca94167 | {
"language": "C#"
} | ```c#
using System.Linq;
namespace CmsEngine.Extensions
{
public static class ObjectExtensions
{
public static object MapTo(this object source, object target)
{
foreach (var sourceProp in source.GetType().GetProperties())
{
var targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
if (targetProp != null && targetProp.GetType().Name == sourceProp.GetType().Name)
{
targetProp.SetValue(target, sourceProp.GetValue(source));
}
}
return target;
}
}
}
```
Check if property has setter | ```c#
using System.Linq;
namespace CmsEngine.Extensions
{
public static class ObjectExtensions
{
public static object MapTo(this object source, object target)
{
foreach (var sourceProp in source.GetType().GetProperties())
{
var targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
if (targetProp != null && targetProp.CanWrite && targetProp.GetSetMethod() != null && targetProp.GetType().Name == sourceProp.GetType().Name)
{
targetProp.SetValue(target, sourceProp.GetValue(source));
}
}
return target;
}
}
}
``` |
cc72b3a2-d767-4dd2-b103-df51d2c57c89 | {
"language": "C#"
} | ```c#
using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
// TODO Need to not include key in serialization when its null to allow mb to use self-signed certificate.
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
```
Set NullHandling to Ignore for key | ```c#
using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
// TODO This won't serialize key, but how does a user of this imposter know it's using the self-signed cert?
[JsonProperty("key", NullValueHandling = NullValueHandling.Ignore)]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
``` |
4a90a8f7-ffd8-4c08-8b17-fd721bef4504 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.Miscellaneous
{
/// ----------------------------------------------------------------------------------------
public class WaitCursor
{
/// ------------------------------------------------------------------------------------
public static void Show()
{
ToggleWaitCursorState(true);
}
/// ------------------------------------------------------------------------------------
public static void Hide()
{
ToggleWaitCursorState(false);
}
/// ------------------------------------------------------------------------------------
private static void ToggleWaitCursorState(bool turnOn)
{
Application.UseWaitCursor = turnOn;
foreach (var frm in Application.OpenForms.Cast<Form>())
{
if (frm.InvokeRequired)
frm.Invoke(new Action(() => frm.Cursor = (turnOn ? Cursors.WaitCursor : Cursors.Default)));
else
frm.Cursor = (turnOn ? Cursors.WaitCursor : Cursors.Default);
}
try
{
// I hate doing this, but setting the cursor property in .Net
// often doesn't otherwise take effect until it's too late.
Application.DoEvents();
}
catch { }
}
}
}
```
Put in defensive code to prevent crash when toggling wait cursor state. | ```c#
using System;
using System.Linq;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.Miscellaneous
{
/// ----------------------------------------------------------------------------------------
public class WaitCursor
{
/// ------------------------------------------------------------------------------------
public static void Show()
{
ToggleWaitCursorState(true);
}
/// ------------------------------------------------------------------------------------
public static void Hide()
{
ToggleWaitCursorState(false);
}
/// ------------------------------------------------------------------------------------
private static void ToggleWaitCursorState(bool turnOn)
{
Application.UseWaitCursor = turnOn;
foreach (var frm in Application.OpenForms.Cast<Form>().ToList())
{
Form form = frm; // Avoid resharper message about accessing foreach variable in closure.
try
{
if (form.InvokeRequired)
form.Invoke(new Action(() => form.Cursor = (turnOn ? Cursors.WaitCursor : Cursors.Default)));
else
form.Cursor = (turnOn ? Cursors.WaitCursor : Cursors.Default);
}
catch
{
// Form may have closed and been disposed. Oh, well.
}
}
try
{
// I hate doing this, but setting the cursor property in .Net
// often doesn't otherwise take effect until it's too late.
Application.DoEvents();
}
catch { }
}
}
}
``` |
e0c4655e-aa99-4440-8a4d-0292fa34c12e | {
"language": "C#"
} | ```c#
using System.Diagnostics;
namespace Renci.SshNet.Abstractions
{
internal static class DiagnosticAbstraction
{
#if FEATURE_DIAGNOSTICS_TRACESOURCE
private static readonly SourceSwitch SourceSwitch = new SourceSwitch("SshNetSwitch");
public static bool IsEnabled(TraceEventType traceEventType)
{
return SourceSwitch.ShouldTrace(traceEventType);
}
private static readonly TraceSource Loggging =
#if DEBUG
new TraceSource("SshNet.Logging", SourceLevels.All);
#else
new TraceSource("SshNet.Logging");
#endif // DEBUG
#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
[Conditional("DEBUG")]
public static void Log(string text)
{
#if FEATURE_DIAGNOSTICS_TRACESOURCE
Loggging.TraceEvent(TraceEventType.Verbose, 1, text);
#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
}
}
}
```
Use the managed thread id as identifier in our trace messages. | ```c#
using System.Diagnostics;
using System.Threading;
namespace Renci.SshNet.Abstractions
{
internal static class DiagnosticAbstraction
{
#if FEATURE_DIAGNOSTICS_TRACESOURCE
private static readonly SourceSwitch SourceSwitch = new SourceSwitch("SshNetSwitch");
public static bool IsEnabled(TraceEventType traceEventType)
{
return SourceSwitch.ShouldTrace(traceEventType);
}
private static readonly TraceSource Loggging =
#if DEBUG
new TraceSource("SshNet.Logging", SourceLevels.All);
#else
new TraceSource("SshNet.Logging");
#endif // DEBUG
#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
[Conditional("DEBUG")]
public static void Log(string text)
{
#if FEATURE_DIAGNOSTICS_TRACESOURCE
Loggging.TraceEvent(TraceEventType.Verbose, Thread.CurrentThread.ManagedThreadId, text);
#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
}
}
}
``` |
c6d3508f-ad0c-446f-947e-a13230c6e1a6 | {
"language": "C#"
} | ```c#
@{
Layout = "default";
Title = "Module";
}
<div class="row">
<div class="span1"></div>
<div class="span10" id="main">
<h1>@Model.Module.Name</h1>
<div class="xmldoc">
@Model.Module.Comment.FullText
</div>
@if (Model.Module.NestedTypes.Length > 0) {
<div>
<table class="table table-bordered type-list">
<thread>
<tr><td>Type</td><td>Description</td></tr>
</thread>
<tbody>
@foreach (var it in Model.Module.NestedTypes) {
<tr>
<td class="type-name">
<a href="@(it.UrlName).html">@Html.Encode(it.Name)</a>
</td>
<td class="xmldoc">@it.Comment.Blurb</td>
</tr>
}
</tbody>
</table>
</div>
}
@RenderPart("members", new {
Header = "Functions and values",
TableHeader = "Function or value",
Members = Model.Module.ValuesAndFuncs
})
@RenderPart("members", new {
Header = "Type extensions",
TableHeader = "Type extension",
Members = Model.Module.TypeExtensions
})
@RenderPart("members", new {
Header = "Active patterns",
TableHeader = "Active pattern",
Members = Model.Module.ActivePatterns
})
</div>
<div class="span1"></div>
</div>```
Add a title for nested types | ```c#
@{
Layout = "default";
Title = "Module";
}
<div class="row">
<div class="span1"></div>
<div class="span10" id="main">
<h1>@Model.Module.Name</h1>
<div class="xmldoc">
@Model.Module.Comment.FullText
</div>
@if (Model.Module.NestedTypes.Length > 0) {
<h2>Nested types</h2>
<div>
<table class="table table-bordered type-list">
<thread>
<tr><td>Type</td><td>Description</td></tr>
</thread>
<tbody>
@foreach (var it in Model.Module.NestedTypes) {
<tr>
<td class="type-name">
<a href="@(it.UrlName).html">@Html.Encode(it.Name)</a>
</td>
<td class="xmldoc">@it.Comment.Blurb</td>
</tr>
}
</tbody>
</table>
</div>
}
@RenderPart("members", new {
Header = "Functions and values",
TableHeader = "Function or value",
Members = Model.Module.ValuesAndFuncs
})
@RenderPart("members", new {
Header = "Type extensions",
TableHeader = "Type extension",
Members = Model.Module.TypeExtensions
})
@RenderPart("members", new {
Header = "Active patterns",
TableHeader = "Active pattern",
Members = Model.Module.ActivePatterns
})
</div>
<div class="span1"></div>
</div>``` |
6055b424-366c-4f69-968b-1a18c694319e | {
"language": "C#"
} | ```c#
namespace BScript.Tests.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BScript.Commands;
using BScript.Expressions;
using BScript.Language;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class CallDotExpressionTests
{
[TestMethod]
public void CreateCallDotExpression()
{
NameExpression nexpr = new NameExpression("foo");
IList<IExpression> exprs = new List<IExpression>() { new ConstantExpression(1), new ConstantExpression(2) };
var expr = new CallDotExpression(nexpr, exprs);
Assert.AreEqual(nexpr, expr.Expression);
Assert.AreSame(exprs, expr.ArgumentExpressions);
}
}
}
```
Fix call dot expression first test | ```c#
namespace BScript.Tests.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BScript.Commands;
using BScript.Expressions;
using BScript.Language;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class CallDotExpressionTests
{
[TestMethod]
public void CreateCallDotExpression()
{
DotExpression dotexpr = new DotExpression(new NameExpression("foo"), "bar");
IList<IExpression> exprs = new List<IExpression>() { new ConstantExpression(1), new ConstantExpression(2) };
var expr = new CallDotExpression(dotexpr, exprs);
Assert.AreEqual(dotexpr, expr.Expression);
Assert.AreSame(exprs, expr.ArgumentExpressions);
}
}
}
``` |
2e91628f-f00b-4b87-967a-ab8bf6e376a1 | {
"language": "C#"
} | ```c#
using UnityEngine;
namespace Pear.InteractionEngine.Interactions
{
/// <summary>
/// Manipulating objects, such as resizing and moving, can be tricky when you have multiple scripts trying the modify the same thing.
/// This class creates an anchor element which is used to help these manipulations
/// </summary>
public class ObjectWithAnchor : MonoBehaviour
{
/// <summary>
/// Used to move and manipulate this object
/// </summary>
public Anchor AnchorElement;
void Awake()
{
if (AnchorElement != null)
return;
// Create the anchor element
GameObject anchor = new GameObject("Anchor");
AnchorElement = anchor.AddComponent<Anchor>();
AnchorElement.Child = this;
AnchorElement.transform.position = transform.position;
anchor.transform.SetParent(transform.parent, true);
transform.SetParent(AnchorElement.transform, true);
}
}
}```
Make sure the anchor is the parent element | ```c#
using UnityEngine;
namespace Pear.InteractionEngine.Interactions
{
/// <summary>
/// Manipulating objects, such as resizing and moving, can be tricky when you have multiple scripts trying the modify the same thing.
/// This class creates an anchor element which is used to help these manipulations
/// </summary>
public class ObjectWithAnchor : MonoBehaviour
{
/// <summary>
/// Used to move and manipulate this object
/// </summary>
public Anchor AnchorElement;
void Awake()
{
if (AnchorElement != null && AnchorElement.transform == transform.parent)
return;
// Create the anchor element
GameObject anchor = new GameObject("Anchor");
AnchorElement = anchor.AddComponent<Anchor>();
AnchorElement.Child = this;
AnchorElement.transform.position = transform.position;
anchor.transform.SetParent(transform.parent, true);
transform.SetParent(AnchorElement.transform, true);
}
}
}``` |
f57f6b44-9b55-40c7-8e9a-c8cfeeef6655 | {
"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.Extensions.ObjectExtensions;
namespace osu.Game.Tests.Visual
{
/// <summary>
/// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests.
/// </summary>
public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene
{
protected override void Update()
{
base.Update();
// note that this will override any mod rate application
MusicController.CurrentTrack.AsNonNull().Tempo.Value = Clock.Rate;
}
}
}
```
Fix a few test scenes | ```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.Diagnostics;
using osu.Framework.Extensions.ObjectExtensions;
namespace osu.Game.Tests.Visual
{
/// <summary>
/// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests.
/// </summary>
public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene
{
protected override void Update()
{
base.Update();
// note that this will override any mod rate application
if (MusicController.TrackLoaded)
{
Debug.Assert(MusicController.CurrentTrack != null);
MusicController.CurrentTrack.Tempo.Value = Clock.Rate;
}
}
}
}
``` |
1ea94ba9-3773-4c55-9ac2-aa105a535acc | {
"language": "C#"
} | ```c#
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
```
Remove namespace and public from console app | ```c#
using System;
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
``` |
6696b114-708a-4ea1-8576-de1f63ddb217 | {
"language": "C#"
} | ```c#
using Pablo.Gallery.Models;
using System.Data.Entity;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System;
using System.Threading;
namespace Pablo.Gallery
{
public class MvcApplication : HttpApplication
{
static MvcApplication()
{
// need to setup here otherwise it won't load embedded dll's properly
Global.Initialize();
}
protected void Application_Start()
{
HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
AuthConfig.RegisterAuth();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
BundleConfig.RegisterExternalBundles(BundleTable.Bundles);
}
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Console.WriteLine("Application error {0}", exception);
}
}
}```
Remove reference to Hibernating Rhinos | ```c#
using Pablo.Gallery.Models;
using System.Data.Entity;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System;
using System.Threading;
namespace Pablo.Gallery
{
public class MvcApplication : HttpApplication
{
static MvcApplication()
{
// need to setup here otherwise it won't load embedded dll's properly
Global.Initialize();
}
protected void Application_Start()
{
//HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
AuthConfig.RegisterAuth();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
BundleConfig.RegisterExternalBundles(BundleTable.Bundles);
}
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Console.WriteLine("Application error {0}", exception);
}
}
}``` |
525586d5-8a85-4a8d-804a-a92ff4f82b0e | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Attributed")]
[assembly: AssemblyDescription("Autofac Extensions for categorized discovery using attributes")]
[assembly: InternalsVisibleTo("Autofac.Tests.Extras.Attributed, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Attributed")]
[assembly: InternalsVisibleTo("Autofac.Tests.Extras.Attributed, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]``` |
eaed7d5c-596b-4b70-b284-867873663954 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using OniBot.Interfaces;
using System.Collections.Generic;
namespace OniBot.CommandConfigs
{
public class SweepConfig : CommandConfig
{
public Dictionary<ulong, string> Equiped = new Dictionary<ulong, string>();
[JsonIgnore]
public override string ConfigKey => "sweep";
}
}
```
Make equipped list a property instead of a field | ```c#
using Newtonsoft.Json;
using OniBot.Interfaces;
using System.Collections.Generic;
namespace OniBot.CommandConfigs
{
public class SweepConfig : CommandConfig
{
public Dictionary<ulong, string> Equiped { get; set; } = new Dictionary<ulong, string>();
[JsonIgnore]
public override string ConfigKey => "sweep";
}
}
``` |
ca8219f0-7509-437b-bcb6-da63b0c5aabe | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Beatmaps
{
public partial class WorkingBeatmap
{
/// <summary>
/// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>.
/// </summary>
protected class VirtualBeatmapTrack : TrackVirtual
{
private const double excess_length = 1000;
private readonly IBeatmap beatmap;
public VirtualBeatmapTrack(IBeatmap beatmap)
{
this.beatmap = beatmap;
updateVirtualLength();
}
protected override void UpdateState()
{
updateVirtualLength();
base.UpdateState();
}
private void updateVirtualLength()
{
var lastObject = beatmap.HitObjects.LastOrDefault();
switch (lastObject)
{
case null:
Length = excess_length;
break;
case IHasEndTime endTime:
Length = endTime.EndTime + excess_length;
break;
default:
Length = lastObject.StartTime + excess_length;
break;
}
}
}
}
}
```
Remove editor functionality from VirtualBeatmapTrack | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Beatmaps
{
public partial class WorkingBeatmap
{
/// <summary>
/// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>.
/// </summary>
protected class VirtualBeatmapTrack : TrackVirtual
{
private const double excess_length = 1000;
public VirtualBeatmapTrack(IBeatmap beatmap)
{
var lastObject = beatmap.HitObjects.LastOrDefault();
switch (lastObject)
{
case null:
Length = excess_length;
break;
case IHasEndTime endTime:
Length = endTime.EndTime + excess_length;
break;
default:
Length = lastObject.StartTime + excess_length;
break;
}
}
}
}
}
``` |
b2f2ceb8-3343-4585-8bd0-759112a0dafe | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.EnterpriseLibraryConfigurator")]
[assembly: AssemblyDescription("Autofac support for Enterprise Library container configuration.")]
[assembly: ComVisible(false)]```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.EnterpriseLibraryConfigurator")]
[assembly: ComVisible(false)]``` |
a111cc41-efac-45f7-9091-7486e76f9976 | {
"language": "C#"
} | ```c#
using System;
using System.Web;
using System.Web.Hosting;
namespace NuGet.Server.Infrastructure {
public class PackageUtility {
internal static string PackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");
public static Uri GetPackageUrl(string path, Uri baseUri) {
return new Uri(baseUri, GetPackageDownloadUrl(path));
}
private static string GetPackageDownloadUrl(string path) {
return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
}
}
}
```
Use the AppSettings 'NuGetPackagePath' if exists and the default ~/Packages otherwise | ```c#
using System;
using System.Web;
using System.Web.Hosting;
using System.Configuration;
namespace NuGet.Server.Infrastructure
{
public class PackageUtility
{
internal static string PackagePhysicalPath;
private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");
static PackageUtility()
{
string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"];
if (string.IsNullOrEmpty(packagePath))
{
PackagePhysicalPath = DefaultPackagePhysicalPath;
}
else
{
PackagePhysicalPath = packagePath;
}
}
public static Uri GetPackageUrl(string path, Uri baseUri)
{
return new Uri(baseUri, GetPackageDownloadUrl(path));
}
private static string GetPackageDownloadUrl(string path)
{
return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
}
}
}
``` |
4c33ceb5-b5da-4f6d-834b-d0329f5a0b69 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Net;
using Google.Protobuf.Reflection;
using KillrVideo.Host.Config;
namespace KillrVideo.Protobuf.ServiceDiscovery
{
/// <summary>
/// Service discovery implementation that just points all service clients to the host/port where they
/// have been configured to run locally.
/// </summary>
public class LocalServiceDiscovery : IFindGrpcServices
{
private readonly IHostConfiguration _hostConfig;
private readonly Lazy<ServiceLocation> _localServicesIp;
public LocalServiceDiscovery(IHostConfiguration hostConfig)
{
if (hostConfig == null) throw new ArgumentNullException(nameof(hostConfig));
_hostConfig = hostConfig;
_localServicesIp = new Lazy<ServiceLocation>(GetLocalGrpcServer);
}
public ServiceLocation Find(ServiceDescriptor service)
{
return _localServicesIp.Value;
}
private ServiceLocation GetLocalGrpcServer()
{
// Get the host/port configuration for the Grpc Server
string host = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostConfigKey);
string portVal = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostPortKey);
int port = int.Parse(portVal);
return new ServiceLocation(host, port);
}
}
}
```
Fix local service discovery now that services are listening on 0.0.0.0 | ```c#
using System;
using Google.Protobuf.Reflection;
using KillrVideo.Host.Config;
namespace KillrVideo.Protobuf.ServiceDiscovery
{
/// <summary>
/// Service discovery implementation that just points all service clients to 'localhost' and the port
/// where they have been configured to run locally.
/// </summary>
public class LocalServiceDiscovery : IFindGrpcServices
{
private readonly IHostConfiguration _hostConfig;
private readonly Lazy<ServiceLocation> _localServicesIp;
public LocalServiceDiscovery(IHostConfiguration hostConfig)
{
if (hostConfig == null) throw new ArgumentNullException(nameof(hostConfig));
_hostConfig = hostConfig;
_localServicesIp = new Lazy<ServiceLocation>(GetLocalGrpcServer);
}
public ServiceLocation Find(ServiceDescriptor service)
{
return _localServicesIp.Value;
}
private ServiceLocation GetLocalGrpcServer()
{
// Get the host/port configuration for the Grpc Server
string host = "localhost";
string portVal = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostPortKey);
int port = int.Parse(portVal);
return new ServiceLocation(host, port);
}
}
}
``` |
521247b6-466f-4281-88f9-14b22db3c15a | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Windows;
namespace Arkivverket.Arkade.UI.Views
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Title = string.Format(UI.Resources.UI.General_WindowTitle, typeof(App).Assembly.GetName().Version);
}
}
}```
Set correct version number in main window | ```c#
using System.Reflection;
using System.Windows;
namespace Arkivverket.Arkade.UI.Views
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Title = string.Format(UI.Resources.UI.General_WindowTitle, "0.3.0"); // Todo - get correct application version from assembly
}
}
}``` |
9c017231-3c43-4c3c-be63-df4fd5c73239 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class ParentedNode : BaseNode
{
public TreeNode Parent { get; set; }
public IEnumerable<ParentedNode> GetParentChain()
{
var chain = new List<ParentedNode>();
ParentedNode current = this;
while (current.Parent != null)
{
chain.Add(current);
current = current.Parent;
}
chain.Reverse();
return chain;
}
public T GetNearestParent<T>() where T : ParentedNode
{
ParentedNode current = this;
while (current.Parent != null)
{
current = current.Parent;
if (current is T)
{
return (T)current;
}
}
return null;
}
}
}
```
Add a debug assert when a node is being reparented. | ```c#
using System.Collections.Generic;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class ParentedNode : BaseNode
{
private TreeNode parent;
public TreeNode Parent
{
get => parent;
set
{
#if DEBUG
if (parent != null)
{
throw new System.InvalidOperationException("A node is being reparented");
}
#endif
parent = value;
}
}
public IEnumerable<ParentedNode> GetParentChain()
{
var chain = new List<ParentedNode>();
ParentedNode current = this;
while (current.Parent != null)
{
chain.Add(current);
current = current.Parent;
}
chain.Reverse();
return chain;
}
public T GetNearestParent<T>() where T : ParentedNode
{
ParentedNode current = this;
while (current.Parent != null)
{
current = current.Parent;
if (current is T)
{
return (T)current;
}
}
return null;
}
}
}
``` |
5eea7dad-fb14-4219-86c1-af53329228e7 | {
"language": "C#"
} | ```c#
using CareerHub.Client.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CareerHub.Client.API.Integrations.Workflows {
internal class WorkflowProgressApi : IWorkflowProgressApi {
private const string ApiBase = "api/integrations/v1/workflows/progress";
private readonly OAuthHttpClient client = null;
public WorkflowProgressApi(string baseUrl, string accessToken) {
client = new OAuthHttpClient(baseUrl, ApiBase, accessToken);
}
public Task<IEnumerable<ProgressModel>> Get(int id) {
return client.GetResource<IEnumerable<ProgressModel>>(id.ToString());
}
}
}
```
Update api to match new URL | ```c#
using CareerHub.Client.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CareerHub.Client.API.Integrations.Workflows {
internal class WorkflowProgressApi : IWorkflowProgressApi {
private const string ApiBase = "api/integrations/v1/workflows";
private readonly OAuthHttpClient client = null;
public WorkflowProgressApi(string baseUrl, string accessToken) {
client = new OAuthHttpClient(baseUrl, ApiBase, accessToken);
}
public Task<IEnumerable<ProgressModel>> Get(int workflowId) {
string resource = GetResource(workflowId);
return client.GetResource<IEnumerable<ProgressModel>>(resource);
}
private string GetResource(int workflowId, string resource = "") {
return String.Format("{0}/progress/{1}", workflowId, resource);
}
}
}
``` |
985d0b62-33b8-403a-9abc-73e00955c443 | {
"language": "C#"
} | ```c#
using Autofac;
using Bit.Model.Events;
using Plugin.Connectivity.Abstractions;
using Prism;
using Prism.Autofac;
using Prism.Events;
using Prism.Ioc;
using Xamarin.Forms;
namespace Bit
{
public abstract class BitApplication : PrismApplication
{
protected BitApplication(IPlatformInitializer platformInitializer = null)
: base(platformInitializer)
{
MainPage = new ContentPage { };
}
protected override void OnInitialized()
{
IConnectivity connectivity = Container.Resolve<IConnectivity>();
IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>();
connectivity.ConnectivityChanged += (sender, e) =>
{
eventAggregator.GetEvent<ConnectivityChangedEvent>()
.Publish(new ConnectivityChangedEvent { IsConnected = e.IsConnected });
};
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.GetBuilder().Register<IContainerProvider>(c => Container).SingleInstance().PreserveExistingDefaults();
}
}
}
```
Set main page of bit application of cs client if no main page is provided (Due error/delay in initialization) | ```c#
using Autofac;
using Bit.Model.Events;
using Plugin.Connectivity.Abstractions;
using Prism;
using Prism.Autofac;
using Prism.Events;
using Prism.Ioc;
using Xamarin.Forms;
namespace Bit
{
public abstract class BitApplication : PrismApplication
{
protected BitApplication(IPlatformInitializer platformInitializer = null)
: base(platformInitializer)
{
if (MainPage == null)
MainPage = new ContentPage { Title = "DefaultPage" };
}
protected override void OnInitialized()
{
IConnectivity connectivity = Container.Resolve<IConnectivity>();
IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>();
connectivity.ConnectivityChanged += (sender, e) =>
{
eventAggregator.GetEvent<ConnectivityChangedEvent>()
.Publish(new ConnectivityChangedEvent { IsConnected = e.IsConnected });
};
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.GetBuilder().Register<IContainerProvider>(c => Container).SingleInstance().PreserveExistingDefaults();
}
}
}
``` |
a310920b-16d1-4b2d-98e3-e89cb32eb49e | {
"language": "C#"
} | ```c#
using static System.Console;
public class Counter
{
public Counter() { }
public int Count;
public Counter Increment()
{
Count++;
return this;
}
}
public static class Program
{
public static readonly Counter printCounter = new Counter();
public static void Main()
{
WriteLine(printCounter.Increment().Coutn);
WriteLine(printCounter.Inrement().Count);
WriteLine(printCoutner.Increment().Count);
}
}```
Expand the misspelled member name test | ```c#
using static System.Console;
public class Counter
{
public Counter() { }
public int Count;
public Counter Increment()
{
Count++;
return this;
}
public Counter Decrement<T>()
{
Count--;
return this;
}
}
public static class Program
{
public static readonly Counter printCounter = new Counter();
public static void Main()
{
WriteLine(printCounter.Increment().Coutn);
WriteLine(printCounter.Inrement().Count);
WriteLine(printCoutner.Increment().Count);
WriteLine(printCounter.Dcrement<int>().Count);
}
}``` |
be9ffc93-5f17-4437-b8ab-9d86d8a57e89 | {
"language": "C#"
} | ```c#
namespace JetBrains.TeamCity.NuGet.Tests
{
public static class NuGetConstants
{
public const string DefaultFeedUrl_v1 = "https://go.microsoft.com/fwlink/?LinkID=206669";
public const string DefaultFeedUrl_v2 = "https://go.microsoft.com/fwlink/?LinkID=230477";
public const string NuGetDevFeed = "https://dotnet.myget.org/F/nuget-build/api/v2/";
}
}```
Use direct nuget public feed URLs | ```c#
namespace JetBrains.TeamCity.NuGet.Tests
{
public static class NuGetConstants
{
public const string DefaultFeedUrl_v1 = "https://packages.nuget.org/v1/FeedService.svc/";
public const string DefaultFeedUrl_v2 = "https://www.nuget.org/api/v2/";
public const string NuGetDevFeed = "https://dotnet.myget.org/F/nuget-build/api/v2/";
}
}
``` |
ef57de44-c30f-46b7-9c3a-623b1764165f | {
"language": "C#"
} | ```c#
namespace Bakery.Cqrs
{
using SimpleInjector;
using System;
using System.Linq;
using System.Threading.Tasks;
public class SimpleInjectorDispatcher
: IDispatcher
{
private readonly Container container;
public SimpleInjectorDispatcher(Container container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
this.container = container;
}
public async Task CommandAsync<TCommand>(TCommand command)
where TCommand : ICommand
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var handlers = container.GetAllInstances<ICommandHandler<TCommand>>().ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(typeof(TCommand));
foreach (var handler in handlers)
await handler.HandleAsync(command);
}
public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
var handlers = container.GetAllInstances(handlerType);
if (!handlers.Any())
throw new NoRegistrationFoundException(query.GetType());
if (handlers.Multiple())
throw new MultipleRegistrationsFoundException(query.GetType());
dynamic handler = handlers.Single();
return await handler.HandleAsync(query as dynamic);
}
}
}
```
Convert candidates to an array. | ```c#
namespace Bakery.Cqrs
{
using SimpleInjector;
using System;
using System.Linq;
using System.Threading.Tasks;
public class SimpleInjectorDispatcher
: IDispatcher
{
private readonly Container container;
public SimpleInjectorDispatcher(Container container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
this.container = container;
}
public async Task CommandAsync<TCommand>(TCommand command)
where TCommand : ICommand
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var handlers = container.GetAllInstances<ICommandHandler<TCommand>>().ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(typeof(TCommand));
foreach (var handler in handlers)
await handler.HandleAsync(command);
}
public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
var handlers = container.GetAllInstances(handlerType).ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(query.GetType());
if (handlers.Multiple())
throw new MultipleRegistrationsFoundException(query.GetType());
dynamic handler = handlers.Single();
return await handler.HandleAsync(query as dynamic);
}
}
}
``` |
eed7c622-95ac-4c67-a567-61590b8bee3a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace PixelPet {
/// <summary>
/// PixelPet workbench instance.
/// </summary>
public class Workbench {
public IList<Color> Palette { get; }
public Bitmap Bitmap { get; private set; }
public Graphics Graphics { get; private set; }
public MemoryStream Stream { get; private set; }
public Workbench() {
this.Palette = new List<Color>();
ClearBitmap(8, 8);
this.Stream = new MemoryStream();
}
public void ClearBitmap(int width, int height) {
Bitmap bmp = null;
try {
bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
SetBitmap(bmp);
} finally {
if (bmp != null) {
bmp.Dispose();
}
}
this.Graphics.Clear(Color.Transparent);
this.Graphics.Flush();
}
public void SetBitmap(Bitmap bmp) {
if (this.Graphics != null) {
this.Graphics.Dispose();
}
if (this.Bitmap != null) {
this.Bitmap.Dispose();
}
this.Bitmap = bmp;
this.Graphics = Graphics.FromImage(this.Bitmap);
}
}
}
```
Fix Clear-Bitmap being completely broken now, oops. | ```c#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace PixelPet {
/// <summary>
/// PixelPet workbench instance.
/// </summary>
public class Workbench {
public IList<Color> Palette { get; }
public Bitmap Bitmap { get; private set; }
public Graphics Graphics { get; private set; }
public MemoryStream Stream { get; private set; }
public Workbench() {
this.Palette = new List<Color>();
ClearBitmap(8, 8);
this.Stream = new MemoryStream();
}
public void ClearBitmap(int width, int height) {
this.Bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
this.Graphics = Graphics.FromImage(this.Bitmap);
this.Graphics.Clear(Color.Transparent);
this.Graphics.Flush();
}
public void SetBitmap(Bitmap bmp) {
if (this.Graphics != null) {
this.Graphics.Dispose();
}
if (this.Bitmap != null) {
this.Bitmap.Dispose();
}
this.Bitmap = bmp;
this.Graphics = Graphics.FromImage(this.Bitmap);
}
}
}
``` |
c75b7a3e-afca-43eb-88b6-28ca7ef4f487 | {
"language": "C#"
} | ```c#
using DeJson;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
namespace HappyFunTimes
{
public class HFTWebFileLoader
{
// TODO: Put this in one place
static private string HFT_WEB_PATH = "HappyFunTimesAutoGeneratedDoNotEdit/";
static private string HFT_WEB_DIR = "HappyFunTimesAutoGeneratedDoNotEdit/__dir__";
static public void LoadFiles(HFTWebFileDB db)
{
TextAsset dirTxt = Resources.Load(HFT_WEB_DIR, typeof(TextAsset)) as TextAsset;
if (dirTxt == null)
{
Debug.LogError("could not load: " + HFT_WEB_DIR);
return;
}
Deserializer deserializer = new Deserializer();
string[] files = deserializer.Deserialize<string[] >(dirTxt.text);
foreach (string file in files)
{
string path = HFT_WEB_PATH + file;
TextAsset asset = Resources.Load(path) as TextAsset;
if (asset == null)
{
Debug.LogError("Could not load: " + path);
}
else
{
db.AddFile(file, asset.bytes);
}
}
}
}
} // namespace HappyFunTimes
```
Use templated version of Resources.Load | ```c#
using DeJson;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
namespace HappyFunTimes
{
public class HFTWebFileLoader
{
// TODO: Put this in one place
static private string HFT_WEB_PATH = "HappyFunTimesAutoGeneratedDoNotEdit/";
static private string HFT_WEB_DIR = "HappyFunTimesAutoGeneratedDoNotEdit/__dir__";
static public void LoadFiles(HFTWebFileDB db)
{
TextAsset dirTxt = Resources.Load<TextAsset>(HFT_WEB_DIR);
if (dirTxt == null)
{
Debug.LogError("could not load: " + HFT_WEB_DIR);
return;
}
Deserializer deserializer = new Deserializer();
string[] files = deserializer.Deserialize<string[] >(dirTxt.text);
foreach (string file in files)
{
string path = HFT_WEB_PATH + file;
TextAsset asset = Resources.Load(path) as TextAsset;
if (asset == null)
{
Debug.LogError("Could not load: " + path);
}
else
{
db.AddFile(file, asset.bytes);
}
}
}
}
} // namespace HappyFunTimes
``` |
12aa610e-6e57-4c68-95e3-b0138b80a677 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using MonoTorrent.BEncoding;
using System.Net;
namespace MonoTorrent.Tracker
{
public abstract class RequestParameters : EventArgs
{
protected internal static readonly string FailureKey = "failure reason";
protected internal static readonly string WarningKey = "warning"; //FIXME: Check this, i know it's wrong!
private IPAddress remoteAddress;
private NameValueCollection parameters;
private BEncodedDictionary response;
public abstract bool IsValid { get; }
public NameValueCollection Parameters
{
get { return parameters; }
}
public BEncodedDictionary Response
{
get { return response; }
}
public IPAddress RemoteAddress
{
get { return remoteAddress; }
protected set { remoteAddress = value; }
}
protected RequestParameters(NameValueCollection parameters, IPAddress address)
{
this.parameters = parameters;
remoteAddress = address;
response = new BEncodedDictionary();
}
}
}
```
Use the correct string for the warning key. (patch by olivier) | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using MonoTorrent.BEncoding;
using System.Net;
namespace MonoTorrent.Tracker
{
public abstract class RequestParameters : EventArgs
{
protected internal static readonly string FailureKey = "failure reason";
protected internal static readonly string WarningKey = "warning message";
private IPAddress remoteAddress;
private NameValueCollection parameters;
private BEncodedDictionary response;
public abstract bool IsValid { get; }
public NameValueCollection Parameters
{
get { return parameters; }
}
public BEncodedDictionary Response
{
get { return response; }
}
public IPAddress RemoteAddress
{
get { return remoteAddress; }
protected set { remoteAddress = value; }
}
protected RequestParameters(NameValueCollection parameters, IPAddress address)
{
this.parameters = parameters;
remoteAddress = address;
response = new BEncodedDictionary();
}
}
}
``` |
df26fa0a-ed8e-4b67-a398-ac7af9c339aa | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using StockportContentApi.Model;
using StockportContentApi.Utils;
using System.Linq;
using System.Threading.Tasks;
namespace StockportContentApi.Services
{
public interface IHealthcheckService
{
Task<Healthcheck> Get();
}
public class HealthcheckService : IHealthcheckService
{
private readonly string _appVersion;
private readonly string _sha;
private readonly IFileWrapper _fileWrapper;
private readonly string _environment;
private readonly ICache _cacheWrapper;
public HealthcheckService(string appVersionPath, string shaPath, IFileWrapper fileWrapper, string environment, ICache cacheWrapper)
{
_fileWrapper = fileWrapper;
_appVersion = GetFirstFileLineOrDefault(appVersionPath, "dev");
_sha = GetFirstFileLineOrDefault(shaPath, string.Empty);
_environment = environment;
_cacheWrapper = cacheWrapper;
}
private string GetFirstFileLineOrDefault(string filePath, string defaultValue)
{
if (_fileWrapper.Exists(filePath))
{
var firstLine = _fileWrapper.ReadAllLines(filePath).FirstOrDefault();
if (!string.IsNullOrEmpty(firstLine))
return firstLine;
}
return defaultValue;
}
public async Task<Healthcheck> Get()
{
// Commented out because it was breaking prod.
//var keys = await _cacheWrapper.GetKeys();
return new Healthcheck(_appVersion, _sha, _environment, new List<RedisValueData>());
}
}
}```
Remove whitespace around app version | ```c#
using System.Collections.Generic;
using StockportContentApi.Model;
using StockportContentApi.Utils;
using System.Linq;
using System.Threading.Tasks;
namespace StockportContentApi.Services
{
public interface IHealthcheckService
{
Task<Healthcheck> Get();
}
public class HealthcheckService : IHealthcheckService
{
private readonly string _appVersion;
private readonly string _sha;
private readonly IFileWrapper _fileWrapper;
private readonly string _environment;
private readonly ICache _cacheWrapper;
public HealthcheckService(string appVersionPath, string shaPath, IFileWrapper fileWrapper, string environment, ICache cacheWrapper)
{
_fileWrapper = fileWrapper;
_appVersion = GetFirstFileLineOrDefault(appVersionPath, "dev");
_sha = GetFirstFileLineOrDefault(shaPath, string.Empty);
_environment = environment;
_cacheWrapper = cacheWrapper;
}
private string GetFirstFileLineOrDefault(string filePath, string defaultValue)
{
if (_fileWrapper.Exists(filePath))
{
var firstLine = _fileWrapper.ReadAllLines(filePath).FirstOrDefault();
if (!string.IsNullOrEmpty(firstLine))
return firstLine.Trim();
}
return defaultValue.Trim();
}
public async Task<Healthcheck> Get()
{
// Commented out because it was breaking prod.
//var keys = await _cacheWrapper.GetKeys();
return new Healthcheck(_appVersion, _sha, _environment, new List<RedisValueData>());
}
}
}``` |
19820a10-5af0-46a5-b859-321f81b35204 | {
"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;
using System.IO;
namespace Microsoft.CodeAnalysis.RulesetToEditorconfig
{
internal static class Program
{
public static int Main(string[] args)
{
if (args.Length < 1 || args.Length > 2)
{
ShowUsage();
return 1;
}
var rulesetFilePath = args[0];
var editorconfigFilePath = args.Length == 2 ?
args[1] :
Path.Combine(Environment.CurrentDirectory, ".editorconfig");
try
{
Converter.GenerateEditorconfig(rulesetFilePath, editorconfigFilePath);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
return 2;
}
Console.WriteLine($"Successfully converted to '{editorconfigFilePath}'");
return 0;
static void ShowUsage()
{
Console.WriteLine("Usage: RulesetToEditorconfigConverter.exe <%ruleset_file%> [<%path_to_editorconfig%>]");
return;
}
}
}
}
```
Fix for one more IDE0078 | ```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;
using System.IO;
namespace Microsoft.CodeAnalysis.RulesetToEditorconfig
{
internal static class Program
{
public static int Main(string[] args)
{
if (args.Length is < 1 or > 2)
{
ShowUsage();
return 1;
}
var rulesetFilePath = args[0];
var editorconfigFilePath = args.Length == 2 ?
args[1] :
Path.Combine(Environment.CurrentDirectory, ".editorconfig");
try
{
Converter.GenerateEditorconfig(rulesetFilePath, editorconfigFilePath);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
return 2;
}
Console.WriteLine($"Successfully converted to '{editorconfigFilePath}'");
return 0;
static void ShowUsage()
{
Console.WriteLine("Usage: RulesetToEditorconfigConverter.exe <%ruleset_file%> [<%path_to_editorconfig%>]");
return;
}
}
}
}
``` |
1cf1ca5d-8f10-4b0e-b15d-24e6e3d57644 | {
"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.
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal sealed class StatisticLogAggregator : AbstractLogAggregator<StatisticLogAggregator.StatisticCounter>
{
protected override StatisticCounter CreateCounter()
{
return new StatisticCounter();
}
public void AddDataPoint(object key, int value)
{
var counter = GetCounter(key);
counter.AddDataPoint(value);
}
public StatisticResult GetStaticticResult(object key)
{
if (TryGetCounter(key, out var counter))
{
return counter.GetStatisticResult();
}
return default;
}
internal sealed class StatisticCounter
{
private int _count;
private int _maximum;
private int _mininum;
private int _total;
public void AddDataPoint(int value)
{
if (_count == 0 || value > _maximum)
{
_maximum = value;
}
if (_count == 0 || value < _mininum)
{
_mininum = value;
}
_count++;
_total += value;
}
public StatisticResult GetStatisticResult()
{
if (_count == 0)
{
return default;
}
else
{
return new StatisticResult(_maximum, _mininum, median: null, mean: _total / _count, range: _maximum - _mininum, mode: null, count: _count);
}
}
}
}
}
```
Add a lock for StatisticCounter | ```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.
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal sealed class StatisticLogAggregator : AbstractLogAggregator<StatisticLogAggregator.StatisticCounter>
{
protected override StatisticCounter CreateCounter()
{
return new StatisticCounter();
}
public void AddDataPoint(object key, int value)
{
var counter = GetCounter(key);
counter.AddDataPoint(value);
}
public StatisticResult GetStaticticResult(object key)
{
if (TryGetCounter(key, out var counter))
{
return counter.GetStatisticResult();
}
return default;
}
internal sealed class StatisticCounter
{
private readonly object _lock = new object();
private int _count;
private int _maximum;
private int _mininum;
private int _total;
public void AddDataPoint(int value)
{
lock (_lock)
{
if (_count == 0 || value > _maximum)
{
_maximum = value;
}
if (_count == 0 || value < _mininum)
{
_mininum = value;
}
_count++;
_total += value;
}
}
public StatisticResult GetStatisticResult()
{
if (_count == 0)
{
return default;
}
else
{
return new StatisticResult(_maximum, _mininum, median: null, mean: _total / _count, range: _maximum - _mininum, mode: null, count: _count);
}
}
}
}
}
``` |
398858c7-46b8-4a17-8fa9-a0f86aa4d990 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace OneDrive
{
public class ThumbnailRetrievalOptions : RetrievalOptions
{
/// <summary>
/// List of thumbnail size names to return
/// </summary>
public string[] SelectThumbnailNames { get; set; }
/// <summary>
/// Retrieve the default thumbnails for an item
/// </summary>
public static ThumbnailRetrievalOptions Default { get { return new ThumbnailRetrievalOptions(); } }
/// <summary>
/// Returns a string like "select=small,medium" that can be used in an expand parameter value
/// </summary>
/// <returns></returns>
public override IEnumerable<ODataOption> ToOptions()
{
List<ODataOption> options = new List<ODataOption>();
SelectOData thumbnailSelect = null;
if (SelectThumbnailNames != null && SelectThumbnailNames.Length > 0)
thumbnailSelect = new SelectOData { FieldNames = SelectThumbnailNames };
options.Add(new ExpandOData
{
PropertyToExpand = ApiConstants.ThumbnailsRelationshipName,
Select = thumbnailSelect
});
return EmptyCollection;
}
}
}
```
Fix thumbnail retrieval options to actually work | ```c#
using System;
using System.Collections.Generic;
namespace OneDrive
{
public class ThumbnailRetrievalOptions : RetrievalOptions
{
/// <summary>
/// List of thumbnail size names to return
/// </summary>
public string[] SelectThumbnailNames { get; set; }
/// <summary>
/// Retrieve the default thumbnails for an item
/// </summary>
public static ThumbnailRetrievalOptions Default { get { return new ThumbnailRetrievalOptions(); } }
/// <summary>
/// Returns a string like "select=small,medium" that can be used in an expand parameter value
/// </summary>
/// <returns></returns>
public override IEnumerable<ODataOption> ToOptions()
{
List<ODataOption> options = new List<ODataOption>();
SelectOData thumbnailSelect = null;
if (SelectThumbnailNames != null && SelectThumbnailNames.Length > 0)
{
thumbnailSelect = new SelectOData { FieldNames = SelectThumbnailNames };
options.Add(thumbnailSelect);
}
return options;
}
}
public static class ThumbnailSize
{
public const string Small = "small";
public const string Medium = "medium";
public const string Large = "large";
public const string SmallSquare = "smallSquare";
public const string MediumSquare = "mediumSquare";
public const string LargeSquare = "largeSquare";
public static string CustomSize(int width, int height, bool cropped)
{
return string.Format("c{0}x{1}{2}", width, height, cropped ? "_Crop" : "");
}
}
}
``` |
89eb4127-7ba8-42ae-876a-ca9f5a79f561 | {
"language": "C#"
} | ```c#
using System;
using InfinniPlatform.Sdk.Types;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace InfinniPlatform.DocumentStorage.MongoDB
{
/// <summary>
/// Реализует логику сериализации и десериализации <see cref="Time"/> для MongoDB.
/// </summary>
internal sealed class MongoTimeBsonSerializer : SerializerBase<Time>
{
public static readonly MongoTimeBsonSerializer Default = new MongoTimeBsonSerializer();
public override Time Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var reader = context.Reader;
var currentBsonType = reader.GetCurrentBsonType();
long totalSeconds;
switch (currentBsonType)
{
case BsonType.Double:
totalSeconds = (long)reader.ReadDouble();
break;
case BsonType.Int64:
totalSeconds = reader.ReadInt64();
break;
case BsonType.Int32:
totalSeconds = reader.ReadInt32();
break;
default:
throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(typeof(Time))}' from BsonType '{currentBsonType}'.");
}
return new Time(totalSeconds);
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Time value)
{
var writer = context.Writer;
writer.WriteDouble(value.TotalSeconds);
}
}
}```
Add BsonSerializer for Date and Time | ```c#
using System;
using InfinniPlatform.Sdk.Types;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace InfinniPlatform.DocumentStorage.MongoDB
{
/// <summary>
/// Реализует логику сериализации и десериализации <see cref="Time"/> для MongoDB.
/// </summary>
internal sealed class MongoTimeBsonSerializer : SerializerBase<Time>
{
public static readonly MongoTimeBsonSerializer Default = new MongoTimeBsonSerializer();
public override Time Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var reader = context.Reader;
var currentBsonType = reader.GetCurrentBsonType();
double totalSeconds;
switch (currentBsonType)
{
case BsonType.Double:
totalSeconds = reader.ReadDouble();
break;
case BsonType.Int64:
totalSeconds = reader.ReadInt64();
break;
case BsonType.Int32:
totalSeconds = reader.ReadInt32();
break;
default:
throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(typeof(Time))}' from BsonType '{currentBsonType}'.");
}
return new Time(totalSeconds);
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Time value)
{
var writer = context.Writer;
writer.WriteDouble(value.TotalSeconds);
}
}
}``` |
29468f82-cd64-4cf7-87c9-eebdf2141f6b | {
"language": "C#"
} | ```c#
using System;
using System.Text;
namespace ExtensionBlocks
{
public class Beef001a : BeefBase
{
public Beef001a(byte[] rawBytes)
: base(rawBytes)
{
if (Signature != 0xbeef001a)
{
throw new Exception($"Signature mismatch! Should be Beef001a but is {Signature}");
}
var len = 0;
var index = 10;
while ((rawBytes[index + len] != 0x0 || rawBytes[index + len + 1] != 0x0))
{
len += 1;
}
var uname = Encoding.Unicode.GetString(rawBytes, index, len + 1);
FileDocumentTypeString = uname;
index += len + 3; // move past string and end of string marker
//is index 24?
//TODO get shell item list
Message =
"Unsupported Extension block. Please report to Report to saericzimmerman@gmail.com to get it added!";
VersionOffset = BitConverter.ToInt16(rawBytes, index);
}
public string FileDocumentTypeString { get; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine();
sb.AppendLine($"File Document Type String: {FileDocumentTypeString}");
return sb.ToString();
}
}
}```
Tweak beef001a to suppress Message when no additional shell items are present | ```c#
using System;
using System.Text;
namespace ExtensionBlocks
{
public class Beef001a : BeefBase
{
public Beef001a(byte[] rawBytes)
: base(rawBytes)
{
if (Signature != 0xbeef001a)
{
throw new Exception($"Signature mismatch! Should be Beef001a but is {Signature}");
}
var len = 0;
var index = 10;
while ((rawBytes[index + len] != 0x0 || rawBytes[index + len + 1] != 0x0))
{
len += 1;
}
var uname = Encoding.Unicode.GetString(rawBytes, index, len + 1);
FileDocumentTypeString = uname;
index += len + 3; // move past string and end of string marker
//is index 24?
//TODO get shell item list
if (index != 38)
{
Message =
"Unsupported Extension block. Please report to Report to saericzimmerman@gmail.com to get it added!";
}
VersionOffset = BitConverter.ToInt16(rawBytes, index);
}
public string FileDocumentTypeString { get; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine();
sb.AppendLine($"File Document Type String: {FileDocumentTypeString}");
return sb.ToString();
}
}
}``` |
66d6c286-b317-45e4-8d1d-7eb6559e5ca7 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestCase : TestCase
{
public override void RunTest()
{
using (var host = new HeadlessGameHost(AppDomain.CurrentDomain.FriendlyName.Replace(' ', '-'), realtime: false))
host.Run(new OsuTestCaseTestRunner(this));
}
public class OsuTestCaseTestRunner : OsuGameBase
{
private readonly OsuTestCase testCase;
public OsuTestCaseTestRunner(OsuTestCase testCase)
{
this.testCase = testCase;
}
protected override void LoadComplete()
{
base.LoadComplete();
Add(new TestCaseTestRunner.TestRunner(testCase));
}
}
}
}
```
Fix test case runs not being correctly isolated on mono | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestCase : TestCase
{
public override void RunTest()
{
Storage storage;
using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
{
storage = host.Storage;
host.Run(new OsuTestCaseTestRunner(this));
}
// clean up after each run
storage.DeleteDirectory(string.Empty);
}
public class OsuTestCaseTestRunner : OsuGameBase
{
private readonly OsuTestCase testCase;
public OsuTestCaseTestRunner(OsuTestCase testCase)
{
this.testCase = testCase;
}
protected override void LoadComplete()
{
base.LoadComplete();
Add(new TestCaseTestRunner.TestRunner(testCase));
}
}
}
}
``` |
18a327a7-1ec3-4bfc-aa12-066f309d71e6 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using Avalonia;
namespace ControlCatalog.NetCore
{
class Program
{
static void Main(string[] args)
{
if (args.Contains("--fbdev"))
AppBuilder.Configure<App>()
.InitializeWithLinuxFramebuffer(tl => tl.Content = new MainView());
else
AppBuilder.Configure<App>()
.UsePlatformDetect()
.Start<MainWindow>();
}
}
}```
Handle console input in fbdev mode | ```c#
using System;
using System.Linq;
using Avalonia;
namespace ControlCatalog.NetCore
{
class Program
{
static void Main(string[] args)
{
if (args.Contains("--fbdev")) AppBuilder.Configure<App>().InitializeWithLinuxFramebuffer(tl =>
{
tl.Content = new MainView();
System.Threading.ThreadPool.QueueUserWorkItem(_ => ConsoleSilencer());
});
else
AppBuilder.Configure<App>()
.UsePlatformDetect()
.Start<MainWindow>();
}
static void ConsoleSilencer()
{
Console.CursorVisible = false;
while (true)
Console.ReadKey();
}
}
}``` |
6b73166c-c040-420a-aefe-a493ae06ddc0 | {
"language": "C#"
} | ```c#
using System;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Resource;
using Moq;
using Xunit;
namespace Glimpse.Test.Core.Resource
{
public class ConfigurationShould
{
[Fact]
public void ReturnProperName()
{
var name = "glimpse_config";
var resource = new ConfigurationResource();
Assert.Equal(name, ConfigurationResource.InternalName);
Assert.Equal(name, resource.Name);
}
[Fact]
public void ReturnNoParameterKeys()
{
var resource = new ConfigurationResource();
Assert.Empty(resource.Parameters);
}
[Fact]
public void Execute()
{
var contextMock = new Mock<IResourceContext>();
var resource = new ConfigurationResource();
Assert.NotNull(resource.Execute(contextMock.Object));
}
}
}```
Fix broken build because of failing test | ```c#
using System;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Framework;
using Glimpse.Core.Resource;
using Glimpse.Core.ResourceResult;
using Moq;
using Xunit;
namespace Glimpse.Test.Core.Resource
{
public class ConfigurationShould
{
[Fact]
public void ReturnProperName()
{
var name = "glimpse_config";
var resource = new ConfigurationResource();
Assert.Equal(name, ConfigurationResource.InternalName);
Assert.Equal(name, resource.Name);
}
[Fact]
public void ReturnNoParameterKeys()
{
var resource = new ConfigurationResource();
Assert.Empty(resource.Parameters);
}
[Fact]
public void NotSupportNonPrivilegedExecution()
{
var resource = new PopupResource();
var contextMock = new Mock<IResourceContext>();
Assert.Throws<NotSupportedException>(() => resource.Execute(contextMock.Object));
}
[Fact(Skip = "Need to build out correct test here")]
public void Execute()
{
var contextMock = new Mock<IResourceContext>();
var configMock = new Mock<IGlimpseConfiguration>();
var resource = new ConfigurationResource();
var result = resource.Execute(contextMock.Object, configMock.Object);
var htmlResourceResult = result as HtmlResourceResult;
Assert.NotNull(result);
}
}
}``` |
4552b8d0-9fd0-4781-a865-6c789bf65ce7 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Android.App;
using Android.Content;
namespace Plugin.FirebasePushNotification
{
[BroadcastReceiver]
public class PushNotificationActionReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
foreach (var key in extras.KeySet())
{
parameters.Add(key, $"{extras.Get(key)}");
System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
}
}
FirebasePushNotificationManager.RegisterAction(parameters);
var manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt(DefaultPushNotificationHandler.ActionNotificationIdKey, -1);
if (notificationId != -1)
{
var notificationTag = extras.GetString(DefaultPushNotificationHandler.ActionNotificationTagKey, string.Empty);
if (notificationTag == null)
{
manager.Cancel(notificationId);
}
else
{
manager.Cancel(notificationTag, notificationId);
}
}
}
}
}
```
Add Enabled = true, Exported = false | ```c#
using System.Collections.Generic;
using Android.App;
using Android.Content;
namespace Plugin.FirebasePushNotification
{
[BroadcastReceiver(Enabled = true, Exported = false)]
public class PushNotificationActionReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
foreach (var key in extras.KeySet())
{
parameters.Add(key, $"{extras.Get(key)}");
System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
}
}
FirebasePushNotificationManager.RegisterAction(parameters);
var manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt(DefaultPushNotificationHandler.ActionNotificationIdKey, -1);
if (notificationId != -1)
{
var notificationTag = extras.GetString(DefaultPushNotificationHandler.ActionNotificationTagKey, string.Empty);
if (notificationTag == null)
{
manager.Cancel(notificationId);
}
else
{
manager.Cancel(notificationTag, notificationId);
}
}
}
}
}
``` |
4e33ac28-4664-49b6-b257-6d61dfd4b206 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using Microsoft.SPOT;
namespace AgentIntervals
{
public delegate void HeartBeatEventHandler(object sender, EventArgs e);
public class HeartBeat
{
private Timer _timer;
private int _period;
public event HeartBeatEventHandler OnHeartBeat;
public HeartBeat(int period)
{
_period = period;
}
private void TimerCallback(object state)
{
if (OnHeartBeat != null)
{
OnHeartBeat(this, new EventArgs());
}
}
public void Start()
{
Start(0);
}
public void Start(int delay)
{
if (_timer != null) return;
_timer = new Timer(TimerCallback, null, delay, _period);
}
public void Stop()
{
if (_timer == null) return;
_timer.Dispose();
_timer = null;
}
public bool Toggle()
{
return Toggle(0);
}
public bool Toggle(int delay)
{
bool started;
if (_timer == null)
{
Start(delay);
started = true;
}
else
{
Stop();
started = false;
}
return started;
}
public void Reset()
{
Reset(0);
}
public void Reset(int delay)
{
Stop();
Start(delay);
}
public void ChangePeriod(int newPeriod)
{
_period = newPeriod;
}
}
}
```
Reset timer if period is changed while it is running. | ```c#
using System;
using System.Threading;
using Microsoft.SPOT;
namespace AgentIntervals
{
public delegate void HeartBeatEventHandler(object sender, EventArgs e);
public class HeartBeat
{
private Timer _timer;
private int _period;
public event HeartBeatEventHandler OnHeartBeat;
public HeartBeat(int period)
{
_period = period;
}
private void TimerCallback(object state)
{
if (OnHeartBeat != null)
{
OnHeartBeat(this, new EventArgs());
}
}
public void Start()
{
Start(0);
}
public void Start(int delay)
{
if (_timer != null) return;
_timer = new Timer(TimerCallback, null, delay, _period);
}
public void Stop()
{
if (_timer == null) return;
_timer.Dispose();
_timer = null;
}
public bool Toggle()
{
return Toggle(0);
}
public bool Toggle(int delay)
{
bool started;
if (_timer == null)
{
Start(delay);
started = true;
}
else
{
Stop();
started = false;
}
return started;
}
public void Reset()
{
Reset(0);
}
public void Reset(int delay)
{
Stop();
Start(delay);
}
public void ChangePeriod(int newPeriod)
{
_period = newPeriod;
if (_timer != null)
{
Reset();
}
}
}
}
``` |
2588ddfb-dac5-4d66-b143-ba99c1c003b7 | {
"language": "C#"
} | ```c#
using AppKit;
using Foundation;
namespace Skia.OSX.Demo
{
[Register ("AppDelegate")]
public partial class AppDelegate : NSApplicationDelegate
{
public AppDelegate ()
{
}
public override void DidFinishLaunching (NSNotification notification)
{
// Insert code here to initialize your application
}
public override void WillTerminate (NSNotification notification)
{
// Insert code here to tear down your application
}
}
}
```
Quit the Mac app after the window is closed | ```c#
using AppKit;
using Foundation;
namespace Skia.OSX.Demo
{
[Register ("AppDelegate")]
public partial class AppDelegate : NSApplicationDelegate
{
public AppDelegate ()
{
}
public override void DidFinishLaunching (NSNotification notification)
{
// Insert code here to initialize your application
}
public override void WillTerminate (NSNotification notification)
{
// Insert code here to tear down your application
}
public override bool ApplicationShouldTerminateAfterLastWindowClosed (NSApplication sender)
{
return true;
}
}
}
``` |
68a02049-8d33-41c1-8187-1e0ceda01e39 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModEasy : ModEasy
{
public override string Description => @"Beats move slower, less accuracy required, and three lives!";
}
}
```
Make EZ mod able to fail in Taiko | ```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 Humanizer;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModEasy : Mod, IApplicableToDifficulty, IApplicableFailOverride
{
public override string Name => "Easy";
public override string Acronym => "EZ";
public override string Description => @"Beats move slower, less accuracy required";
public override IconUsage? Icon => OsuIcon.ModEasy;
public override ModType Type => ModType.DifficultyReduction;
public override double ScoreMultiplier => 0.5;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModHardRock), typeof(ModDifficultyAdjust) };
public void ReadFromDifficulty(BeatmapDifficulty difficulty)
{
}
public void ApplyToDifficulty(BeatmapDifficulty difficulty)
{
const float ratio = 0.5f;
difficulty.CircleSize *= ratio;
difficulty.ApproachRate *= ratio;
difficulty.DrainRate *= ratio;
difficulty.OverallDifficulty *= ratio;
}
public bool PerformFail() => true;
public bool RestartOnFail => false;
}
}
``` |
3acedd55-ad95-4bed-ba15-3033cc1a0c45 | {
"language": "C#"
} | ```c#
using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;
namespace TestStack.FluentMVCTesting.Tests.Internal
{
[TestFixture]
public class ExpressionInspectorShould
{
[Test]
public void Correctly_parse_equality_comparison_with_string_operands()
{
Expression<Func<string, bool>> func = text => text == "any";
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("text => text == \"any\"", actual);
}
[Test]
public void Correctly_parse_equality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number == 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number == 5", actual);
}
[Test]
public void Correctly_parse_inequality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number != 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number != 5", actual);
}
}
}```
Support for parsing equality operator with constant operand. | ```c#
using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;
namespace TestStack.FluentMVCTesting.Tests.Internal
{
[TestFixture]
public class ExpressionInspectorShould
{
[Test]
public void Correctly_parse_equality_comparison_with_string_operands()
{
Expression<Func<string, bool>> func = text => text == "any";
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("text => text == \"any\"", actual);
}
[Test]
public void Correctly_parse_equality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number == 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number == 5", actual);
}
[Test]
public void Correctly_parse_inequality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number != 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number != 5", actual);
}
[Test]
public void Correctly_parse_equality_comparison_with_captured_constant_operand()
{
const int Number = 5;
Expression<Func<int, bool>> func = number => number == Number;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number == " + Number, actual);
}
}
}``` |
9a210909-b7a6-464e-81d8-c6d5f541e59c | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit;
using TeamCityApi.Domain;
using TeamCityApi.Locators;
using TeamCityApi.Tests.Helpers;
using TeamCityApi.Tests.Scenarios;
using TeamCityApi.UseCases;
using Xunit;
using Xunit.Extensions;
namespace TeamCityApi.Tests.UseCases
{
public class CloneRootBuildConfigUseCaseTests
{
[Theory]
[AutoNSubstituteData]
public void Should_clone_root_build_config(
int buildId,
string newNameSyntax,
ITeamCityClient client,
IFixture fixture)
{
var sourceBuildId = buildId.ToString();
var scenario = new SingleBuildScenario(fixture, client, sourceBuildId);
var sut = new CloneRootBuildConfigUseCase(client);
sut.Execute(sourceBuildId, newNameSyntax).Wait();
var newBuildConfigName = scenario.BuildConfig.Name + Consts.SuffixSeparator + newNameSyntax;
client.BuildConfigs.Received()
.CopyBuildConfiguration(scenario.Project.Id, newBuildConfigName, scenario.BuildConfig.Id, Arg.Any<bool>(), Arg.Any<bool>());
}
}
}```
Make clone root build config test more strict | ```c#
using System.Threading.Tasks;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit;
using TeamCityApi.Domain;
using TeamCityApi.Locators;
using TeamCityApi.Tests.Helpers;
using TeamCityApi.Tests.Scenarios;
using TeamCityApi.UseCases;
using Xunit;
using Xunit.Extensions;
namespace TeamCityApi.Tests.UseCases
{
public class CloneRootBuildConfigUseCaseTests
{
[Theory]
[AutoNSubstituteData]
public void Should_clone_root_build_config(
int buildId,
string newNameSyntax,
ITeamCityClient client,
IFixture fixture)
{
var sourceBuildId = buildId.ToString();
var scenario = new SingleBuildScenario(fixture, client, sourceBuildId);
var sut = new CloneRootBuildConfigUseCase(client);
sut.Execute(sourceBuildId, newNameSyntax).Wait();
var newBuildConfigName = scenario.BuildConfig.Name + Consts.SuffixSeparator + newNameSyntax;
client.BuildConfigs.Received(1)
.CopyBuildConfiguration(scenario.Project.Id, newBuildConfigName, scenario.BuildConfig.Id, Arg.Any<bool>(), Arg.Any<bool>());
}
}
}``` |
bb2d8631-a06a-4d98-9a2a-a9e02440bb64 | {
"language": "C#"
} | ```c#
@using System.Configuration;
@{
ViewBag.Title = "Login";
}
<div id="root" style="width: 320px; margin: 40px auto; padding: 10px; border-style: dashed; border-width: 1px;">
embeded area
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-8.2.2.min.js"></script>
<script>
var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');
var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;
lock.show({
container: 'root',
callbackURL: window.location.origin + '/signin-auth0',
responseType: 'code',
authParams: {
scope: 'openid profile',
state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
}
});
</script>
```
Update lock version to 9.0 | ```c#
@using System.Configuration;
@{
ViewBag.Title = "Login";
}
<div id="root" style="width: 320px; margin: 40px auto; padding: 10px; border-style: dashed; border-width: 1px;">
embeded area
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-9.0.js"></script>
<script>
var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');
var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;
lock.show({
container: 'root',
callbackURL: window.location.origin + '/signin-auth0',
responseType: 'code',
authParams: {
scope: 'openid profile',
state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
}
});
</script>
``` |
0625e29d-08f7-42c1-b912-1ed5a703e3e2 | {
"language": "C#"
} | ```c#
using Umbraco.Core;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
[PropertyEditor(Constants.PropertyEditors.TextboxMultipleAlias, "Textarea", "textarea", IsParameterEditor = true)]
public class TextAreaPropertyEditor : PropertyEditor
{
}
}```
Set value type for Textarea to "TEXT". | ```c#
using Umbraco.Core;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
[PropertyEditor(Constants.PropertyEditors.TextboxMultipleAlias, "Textarea", "textarea", IsParameterEditor = true, ValueType = "TEXT")]
public class TextAreaPropertyEditor : PropertyEditor
{
}
}
``` |
770058bf-9a42-41ec-a5fb-c92426192788 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
public static class EditorUtils
{
/// <summary>
/// Deletes all objects in the scene
/// </summary>
public static void ClearScene()
{
foreach (var gameObject in Object.FindObjectsOfType<GameObject>())
{
//only destroy root objects
if (gameObject.transform.parent == null)
{
Object.DestroyImmediate(gameObject);
}
}
}
}
}
```
Rework clear scene method by collecting all roots | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Linq;
using UnityEngine;
namespace HoloToolkit.Unity
{
public static class EditorUtils
{
/// <summary>
/// Deletes all objects in the scene
/// </summary>
public static void ClearScene()
{
foreach (var transform in Object.FindObjectsOfType<Transform>().Select(t => t.root).Distinct().ToList())
{
Object.DestroyImmediate(transform.gameObject);
}
}
}
}
``` |
590bfbbc-8ef6-4ede-a533-f212c8da4ad0 | {
"language": "C#"
} | ```c#
namespace dotless.Core.Parser.Functions
{
using System.Linq;
using Infrastructure;
using Infrastructure.Nodes;
using Tree;
using Utils;
public class RgbaFunction : Function
{
protected override Node Evaluate(Env env)
{
if (Arguments.Count == 2)
{
var color = Guard.ExpectNode<Color>(Arguments[0], this, Location);
var number = Guard.ExpectNode<Number>(Arguments[1], this, Location);
return new Color(color.RGB, number.Value);
}
Guard.ExpectNumArguments(4, Arguments.Count, this, Location);
var args = Guard.ExpectAllNodes<Number>(Arguments, this, Location);
var values = args.Select(n => n.Value).ToList();
var rgb = values.Take(3).ToArray();
var alpha = values[3];
return new Color(rgb, alpha);
}
}
}```
Fix percent conversion to color. | ```c#
namespace dotless.Core.Parser.Functions
{
using System.Linq;
using Infrastructure;
using Infrastructure.Nodes;
using Tree;
using Utils;
public class RgbaFunction : Function
{
protected override Node Evaluate(Env env)
{
if (Arguments.Count == 2)
{
var color = Guard.ExpectNode<Color>(Arguments[0], this, Location);
var number = Guard.ExpectNode<Number>(Arguments[1], this, Location);
return new Color(color.RGB, number.Value);
}
Guard.ExpectNumArguments(4, Arguments.Count, this, Location);
var args = Guard.ExpectAllNodes<Number>(Arguments, this, Location);
var rgb = args.Take(3).Select(n => n.ToNumber(255.0)).ToArray();
var alpha = args[3].ToNumber(1.0);
return new Color(rgb, alpha);
}
}
}``` |
ff025c1e-3ee5-4148-84f4-c591ff9e4baf | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// <copyright file="SharedAssemblyInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
// <summary>
// Assembly global configuration.
// </summary>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure Storage")]
[assembly: AssemblyCopyright("Copyright © 2018 Microsoft Corp.")]
[assembly: AssemblyTrademark("Microsoft ® is a registered trademark of Microsoft Corporation.")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: CLSCompliant(false)]
```
Update DMLib version to 0.8.1.0 | ```c#
//------------------------------------------------------------------------------
// <copyright file="SharedAssemblyInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
// <summary>
// Assembly global configuration.
// </summary>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.8.1.0")]
[assembly: AssemblyFileVersion("0.8.1.0")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure Storage")]
[assembly: AssemblyCopyright("Copyright © 2018 Microsoft Corp.")]
[assembly: AssemblyTrademark("Microsoft ® is a registered trademark of Microsoft Corporation.")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: CLSCompliant(false)]
``` |
7f3c428a-8156-4236-91aa-22a7069e36ce | {
"language": "C#"
} | ```c#
@model SFA.DAS.EmployerAccounts.Web.OrchestratorResponse<SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel>
@{
ViewBag.Title = "Home";
ViewBag.PageID = "page-company-homepage";
}
<div class="das-dashboard-header">
<div class="govuk-width-container das-dashboard-header__border">
<h1 class="das-dashboard-header__title">Your employer account</h1>
<h2 class="das-dashboard-header__account-name">@Model.Data.Account.Name</h2>
</div>
</div>
<main class="govuk-main-wrapper dashboard" id="main-content" role="main">
<div class="govuk-width-container">
<div class="das-panels">
<div class="das-panels__row">
@Html.Action("Row1Panel1", new { model = Model.Data })
@Html.Action("Row1Panel2", new { model = Model.Data })
</div>
<div class="das-panels__row das-panels__row--secondary">
@Html.Action("Row2Panel1", new { model = Model.Data })
@Html.Action("Row2Panel2", new { model = Model.Data })
</div>
</div>
</div>
</main>
```
Update css classes to new styles | ```c#
@model SFA.DAS.EmployerAccounts.Web.OrchestratorResponse<SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel>
@{
ViewBag.Title = "Home";
ViewBag.PageID = "page-company-homepage";
}
<div class="das-dashboard-header das-section--header">
<div class="govuk-width-container das-dashboard-header__border">
<h1 class="govuk-heading-m das-account__title">Your employer account</h1>
<h2 class="govuk-heading-l das-account__account-name">@Model.Data.Account.Name</h2>
</div>
</div>
<main class="govuk-main-wrapper das-section--dashboard" id="main-content" role="main">
<div class="govuk-width-container">
<div class="das-panels">
<div class="das-panels__col das-panels__col--primary">
@Html.Action("Row1Panel1", new { model = Model.Data })
@Html.Action("Row2Panel1", new { model = Model.Data })
</div>
<div class="das-panels__col das-panels__col--secondary">
@Html.Action("Row1Panel2", new { model = Model.Data })
@Html.Action("Row2Panel2", new { model = Model.Data })
</div>
</div>
</div>
</main>
``` |
387eb863-eba1-4f89-aa94-57f9abbb9ea2 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
namespace CefSharp.Example
{
public static class CefExample
{
public const string DefaultUrl = "custom://cefsharp/BindingTest.html";
// Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
private const bool debuggingSubProcess = true;
public static void Init()
{
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
//settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
settings.LogSeverity = LogSeverity.Verbose;
if (debuggingSubProcess)
{
var architecture = Environment.Is64BitProcess ? "x64" : "x86";
settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
});
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
}
}
}
```
Set DebuggingSubProcess = Debugger.IsAttached rather than a hard coded value | ```c#
using System;
using System.Diagnostics;
using System.Linq;
namespace CefSharp.Example
{
public static class CefExample
{
public const string DefaultUrl = "custom://cefsharp/BindingTest.html";
// Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
private static readonly bool DebuggingSubProcess = Debugger.IsAttached;
public static void Init()
{
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
//settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
settings.LogSeverity = LogSeverity.Verbose;
if (DebuggingSubProcess)
{
var architecture = Environment.Is64BitProcess ? "x64" : "x86";
settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
});
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
}
}
}
``` |
4f8c7b48-09d4-488e-b5e7-c25809a8b9e8 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Text;
namespace Eleven41.Helpers
{
public static class JsonHelper
{
public static string Serialize<T>(T obj)
{
return ServiceStack.Text.JsonSerializer.SerializeToString(obj, typeof(T));
}
public static void SerializeToStream<T>(T obj, Stream stream)
{
ServiceStack.Text.JsonSerializer.SerializeToStream(obj, stream);
}
public static T Deserialize<T>(string json)
{
return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(json);
}
public static T DeserializeFromStream<T>(Stream stream)
{
return ServiceStack.Text.JsonSerializer.DeserializeFromStream<T>(stream);
}
}
}```
Add a formated Json serialization option | ```c#
using System;
using System.IO;
using System.Text;
using ServiceStack.Text;
namespace Eleven41.Helpers
{
public static class JsonHelper
{
public static string Serialize<T>(T obj)
{
return JsonSerializer.SerializeToString(obj, typeof(T));
}
public static string SerializeAndFormat<T>(T obj)
{
return obj.SerializeAndFormat();
}
public static void SerializeToStream<T>(T obj, Stream stream)
{
JsonSerializer.SerializeToStream(obj, stream);
}
public static T Deserialize<T>(string json)
{
return JsonSerializer.DeserializeFromString<T>(json);
}
public static T DeserializeFromStream<T>(Stream stream)
{
return JsonSerializer.DeserializeFromStream<T>(stream);
}
}
}``` |
8547eca5-0c5f-4416-8c04-1e3dd0f03ab3 | {
"language": "C#"
} | ```c#
#if DECOMPILE
namespace UELib.Core
{
public partial class UConst : UField
{
/// <summary>
/// Decompiles this object into a text format of:
///
/// const NAME = VALUE;
/// </summary>
/// <returns></returns>
public override string Decompile()
{
return "const " + Name + " = " + Value + ";";
}
}
}
#endif```
Trim the output of constants. | ```c#
#if DECOMPILE
namespace UELib.Core
{
public partial class UConst : UField
{
/// <summary>
/// Decompiles this object into a text format of:
///
/// const NAME = VALUE;
/// </summary>
/// <returns></returns>
public override string Decompile()
{
return "const " + Name + " = " + Value.Trim() + ";";
}
}
}
#endif``` |
915009fe-e25e-42f8-a19a-ebc22f17a8df | {
"language": "C#"
} | ```c#
<div id="challengeInbox" style="display: none;">
<p id="challengeText"></p>
<input type="button" onclick="acceptChallenge()" value="Accept" />
<input type="button" onclick="rejectChallenge()" value="Reject" />
</div>
<script>
function pollChallengeInbox() {
$.getJSON('@Url.Content("~/Poll/ChallengeInbox")', function (data) {
var div = document.getElementById("challengeInbox");
var text = document.getElementById("challengeText");
if (data.challenged) {
text.textContent = "Challenge from " + data.challenger;
div.style = "display: inline-block;";
} else {
div.style = "display: none;";
}
});
}
var challengePoller = window.setInterval(pollChallengeInbox, 5000);
pollChallengeInbox();
function acceptChallenge() {
answer(true);
};
function rejectChallenge() {
answer(false);
};
function answer(accepted) {
$.ajax({
type: "POST",
url: "Challenge/BattleAnswer",
data: { PlayerAccepts: accepted },
success: function (data) {
pollChallengeInbox();
}
});
}
</script>
```
Fix challenge div displaying in Chrome. | ```c#
<div id="challengeInbox" style="display: none;">
<p id="challengeText"></p>
<input type="button" onclick="acceptChallenge()" value="Accept" />
<input type="button" onclick="rejectChallenge()" value="Reject" />
</div>
<script>
function pollChallengeInbox() {
$.getJSON('@Url.Content("~/Poll/ChallengeInbox")', function (data) {
var div = document.getElementById("challengeInbox");
var text = document.getElementById("challengeText");
if (data.challenged) {
text.textContent = "Challenge from " + data.challenger;
div.style.display = "inline-block";
} else {
div.style.display = "none";
}
});
}
var challengePoller = window.setInterval(pollChallengeInbox, 5000);
pollChallengeInbox();
function acceptChallenge() {
answer(true);
};
function rejectChallenge() {
answer(false);
};
function answer(accepted) {
$.ajax({
type: "POST",
url: "Challenge/BattleAnswer",
data: { PlayerAccepts: accepted },
success: function (data) {
pollChallengeInbox();
}
});
}
</script>
``` |
3dafb59d-d908-4b8d-b378-f48bf0e51e15 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Identity;
namespace DragonSpark.Application.Security.Identity;
public readonly record struct Login<T>(ExternalLoginInfo Information, T User);```
Upgrade to allocation as it is used a bit | ```c#
using Microsoft.AspNetCore.Identity;
namespace DragonSpark.Application.Security.Identity;
public sealed record Login<T>(ExternalLoginInfo Information, T User);``` |
0ca638df-b063-4cec-880a-84978ac7ece6 | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
namespace Plivo.Test
{
[TestFixture]
public class TestSignature
{
[Test]
public void TestSignatureV2Pass()
{
string url = "https://answer.url";
string nonce = "12345";
string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
string authToken = "my_auth_token";
Assert.Equals(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken), true);
}
[Test]
public void TestSignatureV2Fail()
{
string url = "https://answer.url";
string nonce = "12345";
string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
string authToken = "my_auth_tokens";
Assert.Equals(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken), false);
}
}
}
```
Fix failing tests on Travis | ```c#
using System;
using NUnit.Framework;
namespace Plivo.Test
{
[TestFixture]
public class TestSignature
{
[Test]
public void TestSignatureV2Pass()
{
string url = "https://answer.url";
string nonce = "12345";
string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
string authToken = "my_auth_token";
Assert.True(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken));
}
[Test]
public void TestSignatureV2Fail()
{
string url = "https://answer.url";
string nonce = "12345";
string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
string authToken = "my_auth_tokens";
Assert.False(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken));
}
}
}
``` |
67343c19-ca95-4534-9841-aa8e6e4f8aad | {
"language": "C#"
} | ```c#
using Silphid.Extensions;
using UnityEngine;
namespace Silphid.Showzup.ListLayouts
{
public class HorizontalListLayout : ListLayout
{
public float HorizontalSpacing;
public float ItemWidth;
protected float ItemOffsetX => ItemWidth + HorizontalSpacing;
public override Rect GetItemRect(int index, Vector2 viewportSize) =>
new Rect(
FirstItemPosition + new Vector2(ItemOffsetX * index, 0),
new Vector2(ItemWidth, viewportSize.y - (Padding.top + Padding.bottom)));
public override Vector2 GetContainerSize(int count, Vector2 viewportSize) =>
new Vector2(
Padding.left + ItemWidth * count + HorizontalSpacing * (count - 1).AtLeast(0) + Padding.right,
viewportSize.y);
public override IndexRange GetVisibleIndexRange(Rect rect) =>
new IndexRange(
((rect.xMin - FirstItemPosition.x) / ItemOffsetX).FloorInt(),
((rect.xMax - FirstItemPosition.x) / ItemOffsetX).FloorInt() + 1);
}
}```
Fix horizontal scroll for Virtual list | ```c#
using Silphid.Extensions;
using UnityEngine;
namespace Silphid.Showzup.ListLayouts
{
public class HorizontalListLayout : ListLayout
{
public float HorizontalSpacing;
public float ItemWidth;
protected float ItemOffsetX => ItemWidth + HorizontalSpacing;
private Rect VisibleRect = new Rect();
public override Rect GetItemRect(int index, Vector2 viewportSize) =>
new Rect(
FirstItemPosition + new Vector2(ItemOffsetX * index, 0),
new Vector2(ItemWidth, viewportSize.y - (Padding.top + Padding.bottom)));
public override Vector2 GetContainerSize(int count, Vector2 viewportSize) =>
new Vector2(
Padding.left + ItemWidth * count + HorizontalSpacing * (count - 1).AtLeast(0) + Padding.right,
viewportSize.y);
public override IndexRange GetVisibleIndexRange(Rect visibleRect)
{
VisibleRect.Set(visibleRect.x*-1, visibleRect.y, visibleRect.width, visibleRect.height);
return new IndexRange(
((VisibleRect.xMin - FirstItemPosition.x) / ItemOffsetX).FloorInt(),
((VisibleRect.xMax - FirstItemPosition.x) / ItemOffsetX).FloorInt() + 1);
}
}
}``` |
8f42c303-9383-45f1-a18b-6c0fbcaf2a60 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
namespace Swashbuckle.AspNetCore.SwaggerGen
{
public class PolymorphicSchemaGenerator : ChainableSchemaGenerator
{
public PolymorphicSchemaGenerator(
SchemaGeneratorOptions options,
ISchemaGenerator rootGenerator,
IContractResolver contractResolver)
: base(options, rootGenerator, contractResolver)
{ }
protected override bool CanGenerateSchemaFor(Type type)
{
var subTypes = Options.SubTypesResolver(type);
return subTypes.Any();
}
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository)
{
var subTypes = Options.SubTypesResolver(type);
return new OpenApiSchema
{
OneOf = subTypes
.Select(subType => RootGenerator.GenerateSchema(subType, schemaRepository))
.ToList()
};
}
}
}```
Make polymorphic schema generation opt-in | ```c#
using System;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
namespace Swashbuckle.AspNetCore.SwaggerGen
{
public class PolymorphicSchemaGenerator : ChainableSchemaGenerator
{
public PolymorphicSchemaGenerator(
SchemaGeneratorOptions options,
ISchemaGenerator rootGenerator,
IContractResolver contractResolver)
: base(options, rootGenerator, contractResolver)
{ }
protected override bool CanGenerateSchemaFor(Type type)
{
return (Options.GeneratePolymorphicSchemas && Options.SubTypesResolver(type).Any());
}
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository)
{
var subTypes = Options.SubTypesResolver(type);
return new OpenApiSchema
{
OneOf = subTypes
.Select(subType => RootGenerator.GenerateSchema(subType, schemaRepository))
.ToList()
};
}
}
}``` |
b0a361cf-fef5-4292-a95e-d512c94815b3 | {
"language": "C#"
} | ```c#
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using LtiLibrary.NetCore.Common;
using LtiLibrary.NetCore.Extensions;
namespace LtiLibrary.NetCore.Profiles
{
public static class ToolConsumerProfileClient
{
/// <summary>
/// Get a ToolConsumerProfile from the service endpoint.
/// </summary>
/// <param name="serviceUrl">The full URL of the ToolConsumerProfile service.</param>
/// <returns>A <see cref="ToolConsumerProfileResponse"/> which includes both the HTTP status code
/// and the <see cref="ToolConsumerProfile"/> if the HTTP status is a success code.</returns>
public static async Task<ToolConsumerProfileResponse> GetToolConsumerProfileAsync(string serviceUrl)
{
var profileResponse = new ToolConsumerProfileResponse();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ToolConsumerProfileMediaType));
var response = await client.GetAsync(serviceUrl);
profileResponse.StatusCode = response.StatusCode;
if (response.IsSuccessStatusCode)
{
profileResponse.ToolConsumerProfile = await response.Content.ReadJsonAsObjectAsync<ToolConsumerProfile>();
}
}
return profileResponse;
}
}
}
```
Add HttpClient to GetToolConsumerProfileAsync convenience method to make it easier to call from an integration test. | ```c#
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using LtiLibrary.NetCore.Common;
using LtiLibrary.NetCore.Extensions;
namespace LtiLibrary.NetCore.Profiles
{
public static class ToolConsumerProfileClient
{
/// <summary>
/// Get a ToolConsumerProfile from the service endpoint.
/// </summary>
/// <param name="client">The HttpClient to use for the request.</param>
/// <param name="serviceUrl">The full URL of the ToolConsumerProfile service.</param>
/// <returns>A <see cref="ToolConsumerProfileResponse"/> which includes both the HTTP status code
/// and the <see cref="ToolConsumerProfile"/> if the HTTP status is a success code.</returns>
public static async Task<ToolConsumerProfileResponse> GetToolConsumerProfileAsync(HttpClient client, string serviceUrl)
{
var profileResponse = new ToolConsumerProfileResponse();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ToolConsumerProfileMediaType));
using (var response = await client.GetAsync(serviceUrl))
{
profileResponse.StatusCode = response.StatusCode;
if (response.IsSuccessStatusCode)
{
profileResponse.ToolConsumerProfile =
await response.Content.ReadJsonAsObjectAsync<ToolConsumerProfile>();
profileResponse.ContentType = response.Content.Headers.ContentType.MediaType;
}
return profileResponse;
}
}
}
}
``` |
f8b22c42-2d4f-4852-a772-928f058ce942 | {
"language": "C#"
} | ```c#
using UnityEngine.Events;
[System.Serializable]
public class LiteNetLibLoadSceneEvent : UnityEvent<string, bool, float>
{
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
```
Remove unused functions (that generate by unity :p) | ```c#
using UnityEngine.Events;
[System.Serializable]
public class LiteNetLibLoadSceneEvent : UnityEvent<string, bool, float>
{
}
``` |
b4681ac9-eb4b-469f-97d9-097acace2dc2 | {
"language": "C#"
} | ```c#
using UnityEngine;
[CreateAssetMenu (menuName = "AI/Actions/Enemy_Attack")]
public class Action_Attack : Action {
public override void Init(StateController controller) {
return;
}
public override void Act(StateController controller) {
}
}
```
Rewrite Action Attack erased by mistake | ```c#
using UnityEngine;
[CreateAssetMenu (menuName = "AI/Actions/Enemy_Attack")]
public class Action_Attack : Action {
[SerializeField] float staminaRequired = 2f;
[SerializeField] float attackDelay = 1f;
[SerializeField] float attackDuration = 1f;
[SerializeField] float attackDamage = 1f;
[SerializeField] float attackRange = 2f;
float timer;
public override void Init(StateController controller) {
Debug.Log("ATTACK STATAE");
timer = attackDelay;
return;
}
public override void Act(StateController controller) {
attackRoutine(controller as Enemy_StateController);
}
private void attackRoutine(Enemy_StateController controller) {
Vector3 targetPosition = controller.chaseTarget.transform.position;
float distanceFromTarget = getDistanceFromTarget(targetPosition, controller);
bool hasStamina = controller.characterStatus.stamina.isEnough(staminaRequired);
if(hasStamina) {
if(timer >= attackDelay) {
timer = attackDelay;
controller.characterStatus.stamina.decrease(staminaRequired);
performAttack(controller, attackDamage, attackDuration);
timer = 0f;
} else {
timer += Time.deltaTime;
}
} else {
timer = attackDelay;
}
}
private void performAttack(Enemy_StateController controller, float attackDamage, float attackDuration) {
controller.anim.SetTrigger("AttackState");
controller.attackHandler.damage = attackDamage;
controller.attackHandler.duration = attackDuration;
controller.attackHandler.hitBox.enabled = true;
}
private float getDistanceFromTarget(Vector3 targetPosition, Enemy_StateController controller) {
Vector3 originPosition = controller.eyes.position;
Vector3 originToTargetVector = targetPosition - originPosition;
float distanceFromTarget = originToTargetVector.magnitude;
return distanceFromTarget;
}
}
``` |
42e4ace6-ce5d-4aa8-b721-3482a499e457 | {
"language": "C#"
} | ```c#
using System.Collections.ObjectModel;
using System.Linq;
using SOVND.Lib.Models;
namespace SOVND.Client.Util
{
public class ChannelDirectory
{
public ObservableCollection<Channel> channels = new ObservableCollection<Channel>();
public bool AddChannel(Channel channel)
{
if (channels.Where(x => x.Name == channel.Name).Count() > 0)
return false;
channels.Add(channel);
return true;
}
}
}```
Fix crash when items are added from non-WPF main thread | ```c#
using System.Collections.ObjectModel;
using System.Linq;
using SOVND.Lib.Models;
namespace SOVND.Client.Util
{
public class ChannelDirectory
{
private readonly SyncHolder _sync;
public ObservableCollection<Channel> channels = new ObservableCollection<Channel>();
public ChannelDirectory(SyncHolder sync)
{
_sync = sync;
}
public bool AddChannel(Channel channel)
{
if (channels.Where(x => x.Name == channel.Name).Count() > 0)
return false;
if (_sync.sync != null)
_sync.sync.Send((x) => channels.Add(channel), null);
else
channels.Add(channel);
return true;
}
}
}``` |
ca9d86ab-b286-46a9-a5ec-c37ce0e57138 | {
"language": "C#"
} | ```c#
namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte Unknown1;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.Unknown1 = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
```
Rename previously unknown GAF field | ```c#
namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte TransparencyIndex;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.TransparencyIndex = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
``` |
5ba2cb16-89db-4d23-9ce1-b170ac1ecb0b | {
"language": "C#"
} | ```c#
using System;
using Xunit;
namespace Cascara.Tests
{
public class AssertExtension : Assert
{
public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
where T : Exception
{
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
}
}
```
Add ThrowsWithMessage() overload with format string | ```c#
using System;
using Xunit;
namespace Cascara.Tests
{
public class AssertExtension : Assert
{
public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
where T : Exception
{
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
public static T ThrowsWithMessage<T>(Func<object> testCode, string fmt, params object[] args)
where T : Exception
{
string message = string.Format(fmt, args);
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
}
}
``` |
48d80aa6-9028-438f-9973-da3bf6182c20 | {
"language": "C#"
} | ```c#
using System;
using Moq;
using Xunit;
using Should;
namespace Foggle
{
public class EnableByHostnameTests
{
[Fact]
public void IsEnabled_ClassMarkedWithFoggleByHostName_TrysToGetListOfHostname()
{
var mockConfig = new Mock<IConfigWrapper>();
Feature.configurationWrapper = mockConfig.Object;
Feature.IsEnabled<TestFeature>().ShouldBeFalse();
mockConfig.Verify(x => x.GetApplicationSetting(It.Is<string>(s => s.EndsWith("Hostnames"))));
}
[Fact]
public void IsEnabled_ClassMarkedWithFoggleByHostName_GetsCurrentHostname()
{
var mockConfig = new Mock<IConfigWrapper>();
Feature.configurationWrapper = mockConfig.Object;
Feature.IsEnabled<TestFeature>();
mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once);
}
[Fact]
public void IsEnabledByHostName_HostnameInList_ReturnsTrue()
{
var mockConfig = new Mock<IConfigWrapper>();
Feature.configurationWrapper = mockConfig.Object;
Feature.IsEnabled<TestFeature>();
mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once);
}
[FoggleByHostname]
class TestFeature : FoggleFeature
{
}
}
}
```
Rename test feature class for hostname tests | ```c#
using System;
using Moq;
using Xunit;
using Should;
namespace Foggle
{
public class EnableByHostnameTests
{
[Fact]
public void IsEnabled_ClassMarkedWithFoggleByHostName_TrysToGetListOfHostname()
{
var mockConfig = new Mock<IConfigWrapper>();
Feature.configurationWrapper = mockConfig.Object;
Feature.IsEnabled<TestHostnameFeature>().ShouldBeFalse();
mockConfig.Verify(x => x.GetApplicationSetting(It.Is<string>(s => s.EndsWith("Hostnames"))));
}
[Fact]
public void IsEnabled_ClassMarkedWithFoggleByHostName_GetsCurrentHostname()
{
var mockConfig = new Mock<IConfigWrapper>();
Feature.configurationWrapper = mockConfig.Object;
Feature.IsEnabled<TestHostnameFeature>();
mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once);
}
[Fact]
public void IsEnabledByHostName_HostnameInList_ReturnsTrue()
{
var mockConfig = new Mock<IConfigWrapper>();
Feature.configurationWrapper = mockConfig.Object;
Feature.IsEnabled<TestHostnameFeature>();
mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once);
}
[FoggleByHostname]
class TestHostnameFeature : FoggleFeature
{
}
}
}
``` |
81b278a5-ba6f-4c0f-8f07-c4e944d226d8 | {
"language": "C#"
} | ```c#
using MacroDiagnostics;
using MacroExceptions;
using MacroGuards;
namespace
produce
{
public class
NuGitModule : Module
{
public override void
Attach(ProduceRepository repository, Graph graph)
{
Guard.NotNull(repository, nameof(repository));
Guard.NotNull(graph, nameof(graph));
var nugitRestore = graph.Command("nugit-restore", _ => Restore(repository));
graph.Dependency(nugitRestore, graph.Command("restore"));
var nugitUpdate = graph.Command("nugit-update", _ => Update(repository));
graph.Dependency(nugitUpdate, graph.Command("update"));
}
static void
Restore(ProduceRepository repository)
{
if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "restore") != 0)
throw new UserException("nugit failed");
}
static void
Update(ProduceRepository repository)
{
if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "update") != 0)
throw new UserException("nugit failed");
}
}
}
```
Add logical operations to NuGit operations | ```c#
using MacroDiagnostics;
using MacroExceptions;
using MacroGuards;
namespace
produce
{
public class
NuGitModule : Module
{
public override void
Attach(ProduceRepository repository, Graph graph)
{
Guard.NotNull(repository, nameof(repository));
Guard.NotNull(graph, nameof(graph));
var nugitRestore = graph.Command("nugit-restore", _ => Restore(repository));
graph.Dependency(nugitRestore, graph.Command("restore"));
var nugitUpdate = graph.Command("nugit-update", _ => Update(repository));
graph.Dependency(nugitUpdate, graph.Command("update"));
}
static void
Restore(ProduceRepository repository)
{
using (LogicalOperation.Start("Restoring NuGit dependencies"))
if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "restore") != 0)
throw new UserException("nugit failed");
}
static void
Update(ProduceRepository repository)
{
using (LogicalOperation.Start("Updating NuGit dependencies"))
if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "update") != 0)
throw new UserException("nugit failed");
}
}
}
``` |
ec441e8c-3a87-4302-8846-69db4fcf89b5 | {
"language": "C#"
} | ```c#
using MediatR;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using System;
using System.Collections.Generic;
using System.Text;
namespace Ordering.Domain.Events
{
/// <summary>
/// Event used when an order is created
/// </summary>
public class OrderStartedDomainEvent : INotification
{
public string UserId { get; private set; }
public int CardTypeId { get; private set; }
public string CardNumber { get; private set; }
public string CardSecurityNumber { get; private set; }
public string CardHolderName { get; private set; }
public DateTime CardExpiration { get; private set; }
public Order Order { get; private set; }
public OrderStartedDomainEvent(Order order, string userId,
int cardTypeId, string cardNumber,
string cardSecurityNumber, string cardHolderName,
DateTime cardExpiration)
{
Order = order;
UserId = userId;
CardTypeId = cardTypeId;
CardNumber = cardNumber;
CardSecurityNumber = cardSecurityNumber;
CardHolderName = cardHolderName;
CardExpiration = cardExpiration;
}
}
}
```
Remove private setters to make class immutable | ```c#
using MediatR;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using System;
using System.Collections.Generic;
using System.Text;
namespace Ordering.Domain.Events
{
/// <summary>
/// Event used when an order is created
/// </summary>
public class OrderStartedDomainEvent : INotification
{
public string UserId { get; }
public int CardTypeId { get; }
public string CardNumber { get; }
public string CardSecurityNumber { get; }
public string CardHolderName { get; }
public DateTime CardExpiration { get; }
public Order Order { get; }
public OrderStartedDomainEvent(Order order, string userId,
int cardTypeId, string cardNumber,
string cardSecurityNumber, string cardHolderName,
DateTime cardExpiration)
{
Order = order;
UserId = userId;
CardTypeId = cardTypeId;
CardNumber = cardNumber;
CardSecurityNumber = cardSecurityNumber;
CardHolderName = cardHolderName;
CardExpiration = cardExpiration;
}
}
}
``` |
b759589a-d025-4833-8457-76de68557ba3 | {
"language": "C#"
} | ```c#
using System;
namespace Hlpr
{
class WarpHelp
{
public static double Distance(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dis;
dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
dis = Math.Pow(dis,0.5);
return dis;
}
public static double Distance(Vector3d v1, Vector3d v2)
{
double dis, x1, x2, y1, y2, z1, z2;
ConvertVector3dToXYZCoords(v1, x1, y1, z1);
ConvertVector3dToXYZCoords(v2, x2, y2, z2);
dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
dis = Math.Pow(dis,0.5);
return dis;
}
}
}```
Fix non-existant ref vars in function calls. | ```c#
using System;
namespace Hlpr
{
class WarpHelp
{
public static double Distance(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dis;
dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
dis = Math.Pow(dis,0.5);
return dis;
}
public static double Distance(Vector3d v1, Vector3d v2)
{
double dis, x1, x2, y1, y2, z1, z2;
ConvertVector3dToXYZCoords(v1, ref x1, ref y1, ref z1);
ConvertVector3dToXYZCoords(v2, ref x2, ref y2, ref z2);
dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
dis = Math.Pow(dis,0.5);
return dis;
}
}
}``` |
8c54274b-83e0-4140-a87d-6ad1ad14ddcb | {
"language": "C#"
} | ```c#
using System;
namespace Umbraco.Web.Models.ContentEditing
{
public class RollbackVersion
{
public int VersionId { get; set; }
public DateTime VersionDate { get; set; }
public string VersionAuthorName { get; set; }
}
}
```
Make the JSON model over the API control be the correct casing & make Mads happy :) | ```c#
using System;
using System.Runtime.Serialization;
namespace Umbraco.Web.Models.ContentEditing
{
[DataContract(Name = "rollbackVersion", Namespace = "")]
public class RollbackVersion
{
[DataMember(Name = "versionId")]
public int VersionId { get; set; }
[DataMember(Name = "versionDate")]
public DateTime VersionDate { get; set; }
[DataMember(Name = "versionAuthorName")]
public string VersionAuthorName { get; set; }
}
}
``` |
e624e75f-999c-4956-9c75-0267f8972e78 | {
"language": "C#"
} | ```c#
using System;
using log4net;
using Quartz;
namespace DCS.Core.Scheduler
{
public sealed class CronTask : IJob
{
private readonly string _cronConfig;
private readonly ILog _logger = LogManager.GetLogger(typeof(CronTask));
private readonly Action _task;
private readonly string _taskName;
public CronTask()
{
}
public CronTask(string taskName, string cronConfig, Action action)
{
_taskName = taskName;
_task = action;
_cronConfig = cronConfig;
}
public string TaskName
{
get { return _taskName; }
}
public string CronConfig
{
get { return _cronConfig; }
}
public void Execute(IJobExecutionContext context)
{
var task = (CronTask)context.MergedJobDataMap.Get("task");
// executes the task
_logger.Info("Executing task : " + task.TaskName);
task._task();
}
}
}```
Set Datawriter executing logs to debug level | ```c#
using System;
using log4net;
using Quartz;
namespace DCS.Core.Scheduler
{
public sealed class CronTask : IJob
{
private readonly string _cronConfig;
private readonly ILog _logger = LogManager.GetLogger(typeof(CronTask));
private readonly Action _task;
private readonly string _taskName;
public CronTask()
{
}
public CronTask(string taskName, string cronConfig, Action action)
{
_taskName = taskName;
_task = action;
_cronConfig = cronConfig;
}
public string TaskName
{
get { return _taskName; }
}
public string CronConfig
{
get { return _cronConfig; }
}
public void Execute(IJobExecutionContext context)
{
var task = (CronTask)context.MergedJobDataMap.Get("task");
// executes the task
_logger.Debug("Executing task : " + task.TaskName);
task._task();
}
}
}``` |
701d4563-76bd-4c5d-af2f-554916dcb95e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zermelo.API.Interfaces;
using Zermelo.API.Services.Interfaces;
namespace Zermelo.API.Services
{
internal class UrlBuilder : IUrlBuilder
{
const string _https = "https://";
const string _baseUrl = "zportal.nl/api";
const string _apiVersion = "v2";
const string _accessToken = "access_token";
public string GetAuthenticatedUrl(IAuthentication auth, string endpoint, Dictionary<string, string> options = null)
{
string url = GetUrl(auth.Host, endpoint, options);
if (url.Contains("?"))
url += "&";
else
url += "?";
url += $"{_accessToken}={auth.Token}";
return url;
}
public string GetUrl(string host, string endpoint, Dictionary<string, string> options = null)
{
string url = $"{_https}{host}.{_baseUrl}/{_apiVersion}/{endpoint}";
if (options != null)
{
url += "?";
foreach (var x in options)
{
url += $"{x.Key}={x.Value}&";
}
url = url.TrimEnd('&');
}
return url;
}
}
}
```
Update REST API version to v3 | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zermelo.API.Interfaces;
using Zermelo.API.Services.Interfaces;
namespace Zermelo.API.Services
{
internal class UrlBuilder : IUrlBuilder
{
const string _https = "https://";
const string _baseUrl = "zportal.nl/api";
const string _apiVersion = "v3";
const string _accessToken = "access_token";
public string GetAuthenticatedUrl(IAuthentication auth, string endpoint, Dictionary<string, string> options = null)
{
string url = GetUrl(auth.Host, endpoint, options);
if (url.Contains("?"))
url += "&";
else
url += "?";
url += $"{_accessToken}={auth.Token}";
return url;
}
public string GetUrl(string host, string endpoint, Dictionary<string, string> options = null)
{
string url = $"{_https}{host}.{_baseUrl}/{_apiVersion}/{endpoint}";
if (options != null)
{
url += "?";
foreach (var x in options)
{
url += $"{x.Key}={x.Value}&";
}
url = url.TrimEnd('&');
}
return url;
}
}
}
``` |
cdf12dca-d48d-4ef0-b47d-54fb00827ffc | {
"language": "C#"
} | ```c#
using InfluxDB.LineProtocol.Collector;
using System;
namespace InfluxDB.LineProtocol
{
public class CollectorConfiguration
{
readonly IPointEmitter _parent;
readonly PipelinedCollectorTagConfiguration _tag;
readonly PipelinedCollectorEmitConfiguration _emitter;
readonly PipelinedCollectorBatchConfiguration _batcher;
public CollectorConfiguration()
: this(null)
{
}
internal CollectorConfiguration(IPointEmitter parent = null)
{
_parent = parent;
_tag = new PipelinedCollectorTagConfiguration(this);
_emitter = new PipelinedCollectorEmitConfiguration(this);
_batcher = new PipelinedCollectorBatchConfiguration(this);
}
public CollectorTagConfiguration Tag
{
get { return _tag; }
}
public CollectorEmitConfiguration WriteTo
{
get { return _emitter; }
}
public CollectorBatchConfiguration Batch
{
get { return _batcher; }
}
public MetricsCollector CreateCollector()
{
Action disposeEmitter;
Action disposeBatcher;
var emitter = _parent;
emitter = _emitter.CreateEmitter(emitter, out disposeEmitter);
emitter = _batcher.CreateEmitter(emitter, out disposeBatcher);
return new PipelinedMetricsCollector(emitter, _tag.CreateEnricher(), () =>
{
if (disposeBatcher != null)
disposeBatcher();
if (disposeEmitter != null)
disposeBatcher();
});
}
}
}
```
Call the disposeEmitter action on dispose | ```c#
using InfluxDB.LineProtocol.Collector;
using System;
namespace InfluxDB.LineProtocol
{
public class CollectorConfiguration
{
readonly IPointEmitter _parent;
readonly PipelinedCollectorTagConfiguration _tag;
readonly PipelinedCollectorEmitConfiguration _emitter;
readonly PipelinedCollectorBatchConfiguration _batcher;
public CollectorConfiguration()
: this(null)
{
}
internal CollectorConfiguration(IPointEmitter parent = null)
{
_parent = parent;
_tag = new PipelinedCollectorTagConfiguration(this);
_emitter = new PipelinedCollectorEmitConfiguration(this);
_batcher = new PipelinedCollectorBatchConfiguration(this);
}
public CollectorTagConfiguration Tag
{
get { return _tag; }
}
public CollectorEmitConfiguration WriteTo
{
get { return _emitter; }
}
public CollectorBatchConfiguration Batch
{
get { return _batcher; }
}
public MetricsCollector CreateCollector()
{
Action disposeEmitter;
Action disposeBatcher;
var emitter = _parent;
emitter = _emitter.CreateEmitter(emitter, out disposeEmitter);
emitter = _batcher.CreateEmitter(emitter, out disposeBatcher);
return new PipelinedMetricsCollector(emitter, _tag.CreateEnricher(), () =>
{
if (disposeBatcher != null)
disposeBatcher();
if (disposeEmitter != null)
disposeEmitter();
});
}
}
}
``` |
1a13e553-3d71-48dd-b906-242cc080b6f4 | {
"language": "C#"
} | ```c#
////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureModule
{
WearableCacheItem[] Get(UUID id);
void Store(UUID id, WearableCacheItem[] data);
}
}
```
Replace proprietary file header with BSD one | ```c#
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureModule
{
WearableCacheItem[] Get(UUID id);
void Store(UUID id, WearableCacheItem[] data);
}
}
``` |
b1b4199c-536c-4442-82f9-de987563470b | {
"language": "C#"
} | ```c#
@model HeadRaceTimingSite.Models.Competition
@{
ViewData["Title"] = Model.Name;
}
<results-list competition-id="@Model.CompetitionId" first-intermediate-name="Barnes" second-intermediate-name="Hammersmith" search-value="{{searchValue}}" show-first-intermediate show-second-intermediate></results-list>
@section titleBar{
<div main-title>@ViewData["Title"]</div>
<paper-icon-button icon="search" id="searchButton"></paper-icon-button>
<paper-icon-button icon="cloud-download" id="downloadButton"></paper-icon-button>
<paper-icon-button class="searchTools" icon="arrow-back" id="backButton"></paper-icon-button>
<paper-input class="searchTools" id="searchBox" value="{{searchValue}}" no-label-float="true"></paper-input>
}
@section scripts{
<script>
window.addEventListener('WebComponentsReady', function (e) {
document.querySelector("#searchButton").addEventListener("click", function (e) {
$("#searchButton").css("display", "none");
$("#downloadButton").css("display", "none");
$("#backButton").css("display", "block");
$("#searchBox").css("display", "block");
$("#searchBox").focus();
$("[main-title]").css("display", "none");
});
document.querySelector("#backButton").addEventListener("click", function (e) {
$("#searchButton").css("display", "inline-block");
$("#downloadButton").css("display", "inline-block");
$("#backButton").css("display", "none");
$("#searchBox").css("display", "none");
$("[main-title]").css("display", "block");
});
document.querySelector("#downloadButton").addEventListener("click", function (e) {
location.href = '/Competition/DetailsAsCsv/@Model.CompetitionId'
});
});
</script>
}```
Remove future features from UI | ```c#
@model HeadRaceTimingSite.Models.Competition
@{
ViewData["Title"] = Model.Name;
}
<results-list competition-id="@Model.CompetitionId" first-intermediate-name="Barnes" second-intermediate-name="Hammersmith" search-value="{{searchValue}}" show-first-intermediate show-second-intermediate></results-list>
@section titleBar{
<div main-title>@ViewData["Title"]</div>
}``` |
23f87841-f342-4937-8559-6a615a3d96dc | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
namespace nunit.v3
{
[TestFixture]
public class FlakyTest
{
[Test]
[Retry(5)]
public void TestFlakyMethod()
{
int result = 0;
try
{
result = FlakyAdd(2, 2);
}
catch(Exception ex)
{
Assert.Fail($"Test failed with unexpected exception, {ex.Message}");
}
Assert.That(result, Is.EqualTo(4));
}
int FlakyAdd(int x, int y)
{
var rand = new Random();
if (rand.NextDouble() > 0.5)
throw new ArgumentOutOfRangeException();
return x + y;
}
[Test]
[Retry(2)]
public void TestFlakySubtract()
{
Assert.That(FlakySubtract(4, 2), Is.EqualTo(2));
}
int count = 0;
int FlakySubtract(int x, int y)
{
count++;
return count == 1 ? 42 : x - y;
}
}
}
```
Make flaky tests a bit less flaky | ```c#
using System;
using NUnit.Framework;
namespace nunit.v3
{
[TestFixture]
public class FlakyTest
{
[Test]
[Retry(5)]
public void TestFlakyMethod()
{
int result = 0;
try
{
result = FlakyAdd(2, 2);
}
catch(Exception ex)
{
Assert.Fail($"Test failed with unexpected exception, {ex.Message}");
}
Assert.That(result, Is.EqualTo(4));
}
int count2 = 0;
int FlakyAdd(int x, int y)
{
if(count2++ == 2)
throw new ArgumentOutOfRangeException();
return x + y;
}
[Test]
[Retry(2)]
public void TestFlakySubtract()
{
Assert.That(FlakySubtract(4, 2), Is.EqualTo(2));
}
int count = 0;
int FlakySubtract(int x, int y)
{
count++;
return count == 1 ? 42 : x - y;
}
}
}
``` |
22f5e495-548d-4a1d-81b3-354a277f7fad | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Information.MediaStore
{
public class MediaStoreSection
{
public string SectionName { get; set; }
public Dictionary<string, string> MediaStoreItems;
private string mediaStoreRoot;
public MediaStoreSection(string sectionName, MediaStore mediaStore)
{
this.mediaStoreRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores", mediaStore.MediaStoreKey, sectionName);
this.SectionName = sectionName;
}
private void LoadMediaStore()
{
try
{
JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Path.Combine(mediaStoreRoot, ".mediastore")));
}
catch
{
return;
}
}
}
}
```
Add methods to manipulate MediaStoreItems | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Information.MediaStore
{
public class MediaStoreSection
{
public string SectionName { get; set; }
public Dictionary<string, string> MediaStoreItems;
private string mediaStoreRoot;
public MediaStoreSection(string sectionName, MediaStore mediaStore)
{
this.mediaStoreRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores", mediaStore.MediaStoreKey, sectionName);
this.SectionName = sectionName;
this.MediaStoreItems = this.LoadMediaStore();
}
private Dictionary<string, string> LoadMediaStore()
{
try
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Path.Combine(mediaStoreRoot, ".mediastore")));
}
catch
{
return new Dictionary<string, string>();
}
}
public void Add(string key, string fileName){
File.Copy(fileName, Path.Combine(this.mediaStoreRoot, Path.GetFileName(fileName));
this.MediaStoreItems.Add(key, Path.GetFileName(fileName));
this.UpdateMediaStoreRecord();
}
public void Remove(string key){
File.Delete(Path.Combine(this.mediaStoreRoot, Path.GetFileName(fileName));
this.MediaStoreItems.Remove(key);
this.UpdateMediaStoreRecord();
}
private void UpdateMediaStoreRecord(){
string record = JsonConvert.SerializeObject(this.MediaStoreItems);
File.WriteAllText(Path.Combine(mediaStoreRoot, ".mediastore"));
}
}
}
``` |
be5f9821-c754-41ef-9364-e9bc8da3b281 | {
"language": "C#"
} | ```c#
/*
JustMock Lite
Copyright © 2019 Progress Software 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 System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return resolver.GetContext();
}
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
```
Add ProfilerInterceptor.GuardInternal() for public APIs even if they are hidden. | ```c#
/*
JustMock Lite
Copyright © 2019 Progress Software 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 System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return ProfilerInterceptor.GuardInternal(() =>
resolver.GetContext()
);
}
public static void CaptureContext()
{
ProfilerInterceptor.GuardInternal(() =>
resolver.CaptureContext()
);
}
}
}
``` |
0f8a201c-36d8-4ecd-b1b2-dc5e0994d091 | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveInitializationStrategiesExtensionMethods.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Deployment.Core
{
using System.Collections.Generic;
using System.Linq;
using Naos.Deployment.Contract;
/// <summary>
/// Additional behavior to add on IHaveInitializationStrategies.
/// </summary>
public static class IHaveInitializationStrategiesExtensionMethods
{
/// <summary>
/// Retrieves the initialization strategies matching the specified type.
/// </summary>
/// <typeparam name="T">Type of initialization strategy to look for.</typeparam>
/// <param name="objectWithInitializationStrategies">Object to operate on.</param>
/// <returns>Collection of initialization strategies matching the type specified.</returns>
public static ICollection<T> GetInitializationStrategiesOf<T>(
this IHaveInitializationStrategies objectWithInitializationStrategies) where T : InitializationStrategyBase
{
var ret = objectWithInitializationStrategies.InitializationStrategies.Select(strat => strat as T).Where(_ => _ != null).ToList();
return ret;
}
}
}
```
Fix potential null ref exception. | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveInitializationStrategiesExtensionMethods.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Deployment.Core
{
using System.Collections.Generic;
using System.Linq;
using Naos.Deployment.Contract;
/// <summary>
/// Additional behavior to add on IHaveInitializationStrategies.
/// </summary>
public static class IHaveInitializationStrategiesExtensionMethods
{
/// <summary>
/// Retrieves the initialization strategies matching the specified type.
/// </summary>
/// <typeparam name="T">Type of initialization strategy to look for.</typeparam>
/// <param name="objectWithInitializationStrategies">Object to operate on.</param>
/// <returns>Collection of initialization strategies matching the type specified.</returns>
public static ICollection<T> GetInitializationStrategiesOf<T>(
this IHaveInitializationStrategies objectWithInitializationStrategies) where T : InitializationStrategyBase
{
var ret =
(objectWithInitializationStrategies.InitializationStrategies ?? new List<InitializationStrategyBase>())
.Select(strat => strat as T).Where(_ => _ != null).ToList();
return ret;
}
}
}
``` |
5a7eb5ef-a374-4eb7-9621-e22bf871f685 | {
"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;
namespace osu.Game.Overlays.Settings
{
public class SettingsTextBox : SettingsItem<string>
{
protected override Drawable CreateControl() => new OutlinedTextBox
{
Margin = new MarginPadding { Top = 5 },
RelativeSizeAxes = Axes.X,
CommitOnFocusLost = true
};
}
}
```
Add exception to catch any incorrect defaults of `Bindable<string>` | ```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.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings
{
public class SettingsTextBox : SettingsItem<string>
{
protected override Drawable CreateControl() => new OutlinedTextBox
{
Margin = new MarginPadding { Top = 5 },
RelativeSizeAxes = Axes.X,
CommitOnFocusLost = true
};
public override Bindable<string> Current
{
get => base.Current;
set
{
if (value.Default == null)
throw new InvalidOperationException($"Bindable settings of type {nameof(Bindable<string>)} should have a non-null default value.");
base.Current = value;
}
}
}
}
``` |
61e8c0cb-89a5-4e29-b191-02cfbbd0abf0 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <exception cref="UserAlreadyInMultiplayerRoom">If the user is already in the requested (or another) room.</exception>
Task<MultiplayerRoom> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
Task LeaveRoom();
}
}```
Add missing methods to server interface | ```c#
using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <exception cref="UserAlreadyInMultiplayerRoom">If the user is already in the requested (or another) room.</exception>
Task<MultiplayerRoom> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
Task LeaveRoom();
/// <summary>
/// Transfer the host of the currently joined room to another user in the room.
/// </summary>
/// <param name="userId">The new user which is to become host.</param>
Task TransferHost(long userId);
/// <summary>
/// As the host, update the settings of the currently joined room.
/// </summary>
/// <param name="settings">The new settings to apply.</param>
Task ChangeSettings(MultiplayerRoomSettings settings);
}
}
``` |
bc4623ec-b3aa-4322-8652-779ea68a8b9c | {
"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;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class DocumentationCommentExtensions
{
public static bool IsMultilineDocComment(this DocumentationCommentTriviaSyntax documentationComment)
{
return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal);
}
}
}
```
Handle null values in IsMultilineDocComment | ```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;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class DocumentationCommentExtensions
{
public static bool IsMultilineDocComment(this DocumentationCommentTriviaSyntax documentationComment)
{
if (documentationComment == null)
{
return false;
}
return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal);
}
}
}
``` |
c21fcca5-2bd8-49e9-a6d0-07bb789fe083 | {
"language": "C#"
} | ```c#
using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
readonly Regex followingAn = new Regex(@"\b(?<article>[Aa]n?) [""()‘’“”$'-]*(?<word>[^\s""()‘’“”$'-]+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
return
from Match m in followingAn.Matches(text)
select new AvsAnSighting { Word = m.Groups["word"].Value + " ", PrecededByAn = m.Groups["article"].Value.Length == 2 };
}
}
}
```
Improve a/an word extraction to avoid problematic cases like "Triple-A classification" | ```c#
using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
readonly Regex followingAn = new Regex(@"(^|[\s""()‘’“”'])(?<article>[Aa]n?) [""()‘’“”$']*(?<word>[^\s""()‘’“”$'-]+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
//watch out for dashes before "A" because of things like "Triple-A annotation"
public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
return
from Match m in followingAn.Matches(text)
select new AvsAnSighting { Word = m.Groups["word"].Value + " ", PrecededByAn = m.Groups["article"].Value.Length == 2 };
}
}
}
``` |
4d03dfe1-c3bf-404d-8b45-a6b6f58c5718 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class SendJobMessageCarrier
{
public SendJobMessageCarrier() { }
public short VehicleId { get; set; }
public string Description { get; set; }
public string UserDescription { get; set; }
public string Body { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool RequiresAddress { get; set; }
public bool AddAddressSummary { get; set; }
public bool UseFirstAddressForSummary { get; set; }
public JobMessageActionNotifications NotificationSettings { get; set; }
public int[] AddressList { get; set; }
public long[] LocationList { get; set; }
public CommsTransports Transport { get; set; }
public bool Urgent { get; set; }
}
}
```
Revert "FLEET-9992: Add extra property to use new long Id's" | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class SendJobMessageCarrier
{
public SendJobMessageCarrier() { }
public short VehicleId { get; set; }
public string Description { get; set; }
public string UserDescription { get; set; }
public string Body { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool RequiresAddress { get; set; }
public bool AddAddressSummary { get; set; }
public bool UseFirstAddressForSummary { get; set; }
public JobMessageActionNotifications NotificationSettings { get; set; }
public long[] AddressList { get; set; }
public CommsTransports Transport { get; set; }
public bool Urgent { get; set; }
}
}
``` |
f61f19bf-169e-4543-b159-459ab88681a9 | {
"language": "C#"
} | ```c#
using UnityEngine;
using NPBehave;
public class NPBehaveExampleHelloBlackboardsAI : MonoBehaviour
{
private Root behaviorTree;
void Start()
{
behaviorTree = new Root(
// toggle the 'toggled' blackboard boolean flag around every 500 milliseconds
new Service(0.5f, () => { behaviorTree.Blackboard.Set("foo", !behaviorTree.Blackboard.GetBool("foo")); },
new Selector(
// Check the 'toggled' flag. Stops.IMMEDIATE_RESTART means that the Blackboard will be observed for changes
// while this or any lower priority branches are executed. If the value changes, the corresponding branch will be
// stopped and it will be immediately jump to the branch that now matches the condition.
new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,
// when 'toggled' is true, this branch will get executed.
new Sequence(
// print out a message ...
new Action(() => Debug.Log("foo")),
// ... and stay here until the `BlackboardValue`-node stops us because the toggled flag went false.
new WaitUntilStopped()
)
),
// when 'toggled' is false, we'll eventually land here
new Sequence(
new Action(() => Debug.Log("bar")),
new WaitUntilStopped()
)
)
)
);
behaviorTree.Start();
}
}
```
Add debugger to HelloWorldBlacksboardAI example | ```c#
using UnityEngine;
using NPBehave;
public class NPBehaveExampleHelloBlackboardsAI : MonoBehaviour
{
private Root behaviorTree;
void Start()
{
behaviorTree = new Root(
// toggle the 'toggled' blackboard boolean flag around every 500 milliseconds
new Service(0.5f, () => { behaviorTree.Blackboard.Set("foo", !behaviorTree.Blackboard.GetBool("foo")); },
new Selector(
// Check the 'toggled' flag. Stops.IMMEDIATE_RESTART means that the Blackboard will be observed for changes
// while this or any lower priority branches are executed. If the value changes, the corresponding branch will be
// stopped and it will be immediately jump to the branch that now matches the condition.
new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,
// when 'toggled' is true, this branch will get executed.
new Sequence(
// print out a message ...
new Action(() => Debug.Log("foo")),
// ... and stay here until the `BlackboardValue`-node stops us because the toggled flag went false.
new WaitUntilStopped()
)
),
// when 'toggled' is false, we'll eventually land here
new Sequence(
new Action(() => Debug.Log("bar")),
new WaitUntilStopped()
)
)
)
);
behaviorTree.Start();
// attach the debugger component if executed in editor (helps to debug in the inspector)
#if UNITY_EDITOR
Debugger debugger = (Debugger)this.gameObject.AddComponent(typeof(Debugger));
debugger.BehaviorTree = behaviorTree;
#endif
}
}
``` |
0cf2a763-ef9a-4a3b-9388-27f221372e5a | {
"language": "C#"
} | ```c#
// Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using AuthServer.Attributes;
using AuthServer.Constants.Net;
using Framework.Database;
using Framework.Database.Auth;
namespace AuthServer.Network.Packets.Handler
{
class AuthHandler
{
[AuthPacket(ClientMessage.State1)]
public static void HandleState1(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.State2)]
public static void HandleState2(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.AuthRequest)]
public static void HandleAuthRequest(Packet packet, AuthSession session)
{
packet.Read<uint>(32);
packet.Read<ulong>(64);
var loginName = packet.ReadString();
Console.WriteLine($"Account '{loginName}' tries to connect.");
var account = DB.Auth.Single<Account>(a => a.Email == loginName);
if (account != null && account.Online)
{
var authComplete = new Packet(ServerMessage.AuthComplete);
authComplete.Write(0, 32);
session.Send(authComplete);
var connectToRealm = new Packet(ServerMessage.ConnectToRealm);
// Data...
session.Send(connectToRealm);
}
}
}
}
```
Disable account online check for now. | ```c#
// Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using AuthServer.Attributes;
using AuthServer.Constants.Net;
using Framework.Database;
using Framework.Database.Auth;
namespace AuthServer.Network.Packets.Handler
{
class AuthHandler
{
[AuthPacket(ClientMessage.State1)]
public static void HandleState1(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.State2)]
public static void HandleState2(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.AuthRequest)]
public static void HandleAuthRequest(Packet packet, AuthSession session)
{
packet.Read<uint>(32);
packet.Read<ulong>(64);
var loginName = packet.ReadString();
Console.WriteLine($"Account '{loginName}' tries to connect.");
//var account = DB.Auth.Single<Account>(a => a.Email == loginName);
//if (account != null && account.Online)
{
var authComplete = new Packet(ServerMessage.AuthComplete);
authComplete.Write(0, 32);
session.Send(authComplete);
var connectToRealm = new Packet(ServerMessage.ConnectToRealm);
// Data...
session.Send(connectToRealm);
}
}
}
}
``` |
8de86c76-5b2a-42a5-a471-347d2e6f1709 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DropdownLanguageFontUpdater : MonoBehaviour
{
[SerializeField]
private Text textComponent;
void Start ()
{
var language = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1];
if (language.overrideFont != null)
{
textComponent.font = language.overrideFont;
if (language.forceUnbold)
textComponent.fontStyle = FontStyle.Normal;
}
}
void Update ()
{
}
}
```
Fix incorrect font indexing in language dropdown | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DropdownLanguageFontUpdater : MonoBehaviour
{
[SerializeField]
private Text textComponent;
void Start ()
{
var languages = LocalizationManager.instance.getAllLanguages();
LocalizationManager.Language language = languages[0];
//Determine langauge index based on sibling position and selectable languages
int index = 0;
int objectIndex = transform.GetSiblingIndex() - 1;
for (int i = 0; i < languages.Length; i++)
{
if (!languages[i].disableSelect)
{
if (index >= objectIndex)
{
language = languages[i];
Debug.Log(textComponent.text + " is " + language.getLanguageID());
break;
}
index++;
}
}
if (language.overrideFont != null)
{
textComponent.font = language.overrideFont;
if (language.forceUnbold)
textComponent.fontStyle = FontStyle.Normal;
}
}
void Update ()
{
}
}
``` |
1f2f38c2-807b-4e5c-86aa-f06f26f1aab3 | {
"language": "C#"
} | ```c#
#if !NETCOREAPP
using System.ComponentModel;
#endif
using System.IO;
#if !NETCOREAPP
using System.Runtime.InteropServices;
#endif
namespace winsw.Util
{
public static class FileHelper
{
public static void MoveOrReplaceFile(string sourceFileName, string destFileName)
{
#if NETCOREAPP
File.Move(sourceFileName, destFileName, true);
#else
string sourceFilePath = Path.GetFullPath(sourceFileName);
string destFilePath = Path.GetFullPath(destFileName);
if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
{
throw new Win32Exception();
}
#endif
}
#if !NETCOREAPP
private static class NativeMethods
{
internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;
internal const uint MOVEFILE_COPY_ALLOWED = 0x02;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW")]
internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
}
#endif
}
}
```
Throw correct exceptions for IO errors | ```c#
#if !NETCOREAPP
using System;
#endif
using System.IO;
#if !NETCOREAPP
using System.Runtime.InteropServices;
#endif
namespace winsw.Util
{
public static class FileHelper
{
public static void MoveOrReplaceFile(string sourceFileName, string destFileName)
{
#if NETCOREAPP
File.Move(sourceFileName, destFileName, true);
#else
string sourceFilePath = Path.GetFullPath(sourceFileName);
string destFilePath = Path.GetFullPath(destFileName);
if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
{
throw GetExceptionForLastWin32Error(sourceFilePath);
}
#endif
}
#if !NETCOREAPP
private static Exception GetExceptionForLastWin32Error(string path) => Marshal.GetLastWin32Error() switch
{
2 => new FileNotFoundException(null, path), // ERROR_FILE_NOT_FOUND
3 => new DirectoryNotFoundException(), // ERROR_PATH_NOT_FOUND
5 => new UnauthorizedAccessException(), // ERROR_ACCESS_DENIED
_ => new IOException()
};
private static class NativeMethods
{
internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;
internal const uint MOVEFILE_COPY_ALLOWED = 0x02;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW")]
internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
}
#endif
}
}
``` |
be79a599-bd0a-4898-ac1d-a64dcca8af35 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac;
using Crane.Core.Configuration.Modules;
using Crane.Core.IO;
using log4net;
namespace Crane.Integration.Tests.TestUtilities
{
public static class ioc
{
private static IContainer _container;
public static T Resolve<T>() where T : class
{
if (_container == null)
{
_container = BootStrap.Start();
}
if (_container.IsRegistered<T>())
{
return _container.Resolve<T>();
}
return ResolveUnregistered(_container, typeof(T)) as T;
}
public static object ResolveUnregistered(IContainer container, Type type)
{
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
try
{
var parameters = constructor.GetParameters();
var parameterInstances = new List<object>();
foreach (var parameter in parameters)
{
var service = container.Resolve(parameter.ParameterType);
if (service == null) throw new Exception("Unkown dependency");
parameterInstances.Add(service);
}
return Activator.CreateInstance(type, parameterInstances.ToArray());
}
catch (Exception)
{
}
}
Debugger.Launch();
throw new Exception("No contructor was found that had all the dependencies satisfied.");
}
}
}```
Add better error logging to see why mono build is failing | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac;
using Crane.Core.Configuration.Modules;
using Crane.Core.IO;
using log4net;
namespace Crane.Integration.Tests.TestUtilities
{
public static class ioc
{
private static IContainer _container;
private static readonly ILog _log = LogManager.GetLogger(typeof(Run));
public static T Resolve<T>() where T : class
{
if (_container == null)
{
_container = BootStrap.Start();
}
if (_container.IsRegistered<T>())
{
return _container.Resolve<T>();
}
return ResolveUnregistered(_container, typeof(T)) as T;
}
public static object ResolveUnregistered(IContainer container, Type type)
{
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
try
{
var parameters = constructor.GetParameters();
var parameterInstances = new List<object>();
foreach (var parameter in parameters)
{
var service = container.Resolve(parameter.ParameterType);
if (service == null) throw new Exception("Unkown dependency");
parameterInstances.Add(service);
}
return Activator.CreateInstance(type, parameterInstances.ToArray());
}
catch (Exception exception)
{
_log.ErrorFormat("Error trying to create an instance of {0}. {1}{2}", type.FullName, Environment.NewLine, exception.ToString());
}
}
throw new Exception("No contructor was found that had all the dependencies satisfied.");
}
}
}``` |
47cd2d5b-6736-4580-bcd8-f1e906b6d46b | {
"language": "C#"
} | ```c#
using System.Web;
using System.Web.Mvc;
using Pelasoft.AspNet.Mvc.Slack;
using System.Configuration;
namespace Pelasoft.AspNet.Mvc.Slack.TestWeb
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
var slackReport =
new WebHookErrorReportFilter(
new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
{
ChannelName = ConfigurationManager.AppSettings["slack:channel"],
UserName = ConfigurationManager.AppSettings["slack:username"],
IconEmoji = ConfigurationManager.AppSettings["slack:iconEmoji"],
AttachmentColor = ConfigurationManager.AppSettings["slack:color"],
AttachmentTitle = ConfigurationManager.AppSettings["slack:title"],
AttachmentTitleLink = ConfigurationManager.AppSettings["slack:link"],
Text = ConfigurationManager.AppSettings["slack:text"],
}
)
{
IgnoreHandled = true,
IgnoreExceptionTypes = new[] { typeof(System.ApplicationException) },
};
filters.Add(slackReport, 1);
}
}
}```
Add tests for new eventing behavior. | ```c#
using System.Web;
using System.Web.Mvc;
using Pelasoft.AspNet.Mvc.Slack;
using System.Configuration;
namespace Pelasoft.AspNet.Mvc.Slack.TestWeb
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
var slackReport =
new WebHookErrorReportFilter(
new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
{
ChannelName = ConfigurationManager.AppSettings["slack:channel"],
UserName = ConfigurationManager.AppSettings["slack:username"],
IconEmoji = ConfigurationManager.AppSettings["slack:iconEmoji"],
AttachmentColor = ConfigurationManager.AppSettings["slack:color"],
AttachmentTitle = ConfigurationManager.AppSettings["slack:title"],
AttachmentTitleLink = ConfigurationManager.AppSettings["slack:link"],
Text = ConfigurationManager.AppSettings["slack:text"],
}
)
{
IgnoreHandled = true,
IgnoreExceptionTypes = new[] { typeof(System.ApplicationException) },
};
filters.Add(slackReport, 1);
var slackReportEvented = new WebHookErrorReportFilter();
slackReportEvented.OnExceptionReporting += slackReportEvented_OnExceptionReporting;
filters.Add(slackReportEvented);
}
static void slackReportEvented_OnExceptionReporting(ExceptionReportingEventArgs args)
{
args.Options = new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
{
Text = "Options reported via the event.",
ChannelName = ConfigurationManager.AppSettings["slack:channel"],
};
// args.CancelReport = true;
}
}
}``` |
7a0d9c71-34b8-4ffa-8789-834794ab1c16 | {
"language": "C#"
} | ```c#
using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
namespace SevenDigital.Api.Schema.ReleaseEndpoint
{
[XmlRoot("editorial")]
[ApiEndpoint("release/editorial")]
[Serializable]
public class ReleaseEditorial : HasReleaseIdParameter
{
[XmlElement("review")]
public Review Review { get; set; }
[XmlElement("staffRecommendation")]
public Review StaffRecommendation { get; set; }
[XmlElement("promotionalText")]
public string PromotionalText { get; set; }
}
public class Review
{
[XmlElement("text")]
public string Text { get; set; }
}
}
```
Update the release/editorial endpoint schema | ```c#
using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
namespace SevenDigital.Api.Schema.ReleaseEndpoint
{
[XmlRoot("editorial")]
[ApiEndpoint("release/editorial")]
[Serializable]
public class ReleaseEditorial : HasReleaseIdParameter
{
[XmlElement("review")]
public TextItem Review { get; set; }
[XmlElement("promotionalText")]
public TextItem PromotionalText { get; set; }
}
public class TextItem
{
[XmlElement("text")]
public string Text { get; set; }
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.