doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
59f41e86-ba9c-429d-83cf-4a71a7f7a8c5 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.ComponentModel;
using Telegram.Bot.Types.InputMessageContents;
namespace Telegram.Bot.Types.InlineQueryResults
{
/// <summary>
/// Represents a <see cref="Game"/>.
/// </summary>
/// <seealso cref="InlineQueryResultNew" />
[JsonObject(MemberSerialization = MemberSerialization.OptIn,
NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class InlineQueryResultGame : InlineQueryResult
{
/// <summary>
/// Initializes a new inline query result
/// </summary>
public InlineQueryResultGame()
{
Type = InlineQueryResultType.Game;
}
/// <summary>
/// Short name of the game.
/// </summary>
[JsonProperty(Required = Required.Always)]
public string GameShortName { get; set; }
#pragma warning disable 1591
[JsonIgnore]
[EditorBrowsable(EditorBrowsableState.Never)]
public new string Title { get; set; }
[JsonIgnore]
[EditorBrowsable(EditorBrowsableState.Never)]
public new InputMessageContent InputMessageContent { get; set; }
#pragma warning restore 1591
}
}
```
Fix game inline query result | ```c#
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Telegram.Bot.Types.InlineQueryResults
{
/// <summary>
/// Represents a <see cref="Game"/>.
/// </summary>
/// <seealso cref="InlineQueryResult" />
[JsonObject(MemberSerialization = MemberSerialization.OptIn,
NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class InlineQueryResultGame : InlineQueryResult
{
/// <summary>
/// Initializes a new inline query result
/// </summary>
public InlineQueryResultGame()
{
Type = InlineQueryResultType.Game;
}
/// <summary>
/// Short name of the game.
/// </summary>
[JsonProperty(Required = Required.Always)]
public string GameShortName { get; set; }
}
}
``` |
8bcd05f7-3046-4b6a-8e8b-3e95ba1f215c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace ProjectTracker.AppServerCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
Csla.Configuration.ConfigurationManager.AppSettings["DalManagerType"] =
"ProjectTracker.DalMock.DalManager,ProjectTracker.DalMock";
}
}
}
```
Update to use CSLA configuration | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Csla.Configuration;
namespace ProjectTracker.AppServerCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCsla();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseCsla();
ConfigurationManager.AppSettings["DalManagerType"] =
"ProjectTracker.DalMock.DalManager,ProjectTracker.DalMock";
}
}
}
``` |
69dcbaaf-dff4-46e8-be60-a154ff3e35f6 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
namespace UAOOI.SemanticData.AddressSpaceTestTool
{
class Program
{
internal static void Main(string[] args)
{
FileInfo _fileToRead = GetFileToRead(args);
ValidateFile(_fileToRead);
}
internal static void ValidateFile(FileInfo _fileToRead)
{
throw new NotImplementedException();
}
internal static FileInfo GetFileToRead(string[] args)
{
throw new NotImplementedException();
}
}
}
```
Implement AddressSpaceComplianceTestTool - added top level exception handling. | ```c#
using System;
using System.IO;
namespace UAOOI.SemanticData.AddressSpaceTestTool
{
class Program
{
internal static void Main(string[] args)
{
try
{
FileInfo _fileToRead = GetFileToRead(args);
ValidateFile(_fileToRead);
}
catch (Exception ex)
{
Console.WriteLine(String.Format("Program stoped by the exception: {0}", ex.Message));
}
Console.Write("Press ENter to close this window.......");
Console.Read();
}
internal static void ValidateFile(FileInfo _fileToRead)
{
throw new NotImplementedException();
}
internal static FileInfo GetFileToRead(string[] args)
{
throw new NotImplementedException();
}
}
}
``` |
3414e945-2c18-4998-8efc-879629963737 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAccessExamples.Core.Actions;
using DataAccessExamples.Core.ViewModels;
namespace DataAccessExamples.Core.Services.Employee
{
public class LazyOrmEmployeeService : IEmployeeService
{
public void AddEmployee(AddEmployee action)
{
throw new NotImplementedException();
}
public EmployeeList ListRecentHires()
{
throw new NotImplementedException();
}
}
}
```
Add (intentionally) broken Lazy ORM Employee service | ```c#
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DataAccessExamples.Core.Actions;
using DataAccessExamples.Core.Data;
using DataAccessExamples.Core.ViewModels;
namespace DataAccessExamples.Core.Services.Employee
{
public class LazyOrmEmployeeService : IEmployeeService
{
private readonly EmployeesContext context;
public LazyOrmEmployeeService(EmployeesContext context)
{
this.context = context;
}
public void AddEmployee(AddEmployee action)
{
var employee = Mapper.Map<Data.Employee>(action);
employee.DepartmentEmployees.Add(new DepartmentEmployee
{
Employee = employee,
DepartmentCode = action.DepartmentCode,
FromDate = action.HireDate,
ToDate = DateTime.MaxValue
});
context.Employees.Add(employee);
context.SaveChanges();
}
public EmployeeList ListRecentHires()
{
return new EmployeeList
{
Employees = context.Employees
.Where(e => e.HireDate > DateTime.Now.AddDays(-7))
.OrderByDescending(e => e.HireDate)
};
}
}
}
``` |
7c930851-4456-46e6-92c1-df8085c8b83b | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using Version = Msg.Domain.Version;
using System;
using System.Net.Sockets;
using System.Net;
namespace Msg.Acceptance.Tests
{
class GarbageSpewingClient
{
TcpClient client;
public async Task<byte[]> ConnectAsync() {
client = new TcpClient ();
await client.ConnectAsync (IPAddress.Loopback, 1984);
var stream = client.GetStream ();
await stream.WriteAsync (new byte[] { 1, 9, 8, 4 }, 0, 4);
var buffer = new byte[8];
await stream.ReadAsync (buffer, 0, 8);
return buffer;
}
public bool IsConnected()
{
return client != null && client.Connected;
}
}
}
```
Update garbage spewing client to use test doubles namespace. | ```c#
using System.Threading.Tasks;
using Version = Msg.Domain.Version;
using System;
using System.Net.Sockets;
using System.Net;
namespace Msg.Acceptance.Tests.TestDoubles
{
class GarbageSpewingClient
{
TcpClient client;
public async Task<byte[]> ConnectAsync() {
client = new TcpClient ();
await client.ConnectAsync (IPAddress.Loopback, 1984);
var stream = client.GetStream ();
await stream.WriteAsync (new byte[] { 1, 9, 8, 4 }, 0, 4);
var buffer = new byte[8];
await stream.ReadAsync (buffer, 0, 8);
return buffer;
}
public bool IsConnected()
{
return client != null && client.Connected;
}
}
}
``` |
79cdec20-a797-43f7-89f2-e3b1f954d3e8 | {
"language": "C#"
} | ```c#
using System;
using JabbR.Models;
using JabbR.Services;
namespace JabbR.Commands
{
[Command("flag", "Flag_CommandInfo", "Iso 3366-2 Code", "user")]
public class FlagCommand : UserCommand
{
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args)
{
if (args.Length == 0)
{
// Clear the flag.
callingUser.Flag = null;
}
else
{
// Set the flag.
string isoCode = String.Join(" ", args[0]).ToLowerInvariant();
ChatService.ValidateIsoCode(isoCode);
callingUser.Flag = isoCode;
}
context.NotificationService.ChangeFlag(callingUser);
context.Repository.CommitChanges();
}
}
}```
Update to use correct ISO code | ```c#
using System;
using JabbR.Models;
using JabbR.Services;
namespace JabbR.Commands
{
[Command("flag", "Flag_CommandInfo", "Iso 3166-2 Code", "user")]
public class FlagCommand : UserCommand
{
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args)
{
if (args.Length == 0)
{
// Clear the flag.
callingUser.Flag = null;
}
else
{
// Set the flag.
string isoCode = String.Join(" ", args[0]).ToLowerInvariant();
ChatService.ValidateIsoCode(isoCode);
callingUser.Flag = isoCode;
}
context.NotificationService.ChangeFlag(callingUser);
context.Repository.CommitChanges();
}
}
}
``` |
a234179a-0f19-440c-ad8c-f2aca7405e90 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Objects.Get.Users
{
using Basic;
using Newtonsoft.Json;
public class TraktUserImages
{
[JsonProperty(PropertyName = "avatar")]
public TraktImage Avatar { get; set; }
}
}
```
Add get best id method for user images. | ```c#
namespace TraktApiSharp.Objects.Get.Users
{
using Basic;
using Newtonsoft.Json;
/// <summary>A collection of images and image sets for a Trakt user.</summary>
public class TraktUserImages
{
/// <summary>Gets or sets the avatar image.</summary>
[JsonProperty(PropertyName = "avatar")]
public TraktImage Avatar { get; set; }
}
}
``` |
dc51679b-933b-4ec7-8a51-7ddf6d44420f | {
"language": "C#"
} | ```c#
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Markup.Xaml;
using ReactiveUI;
using System;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class CoinListView : UserControl
{
public static readonly StyledProperty<bool> SelectAllNonPrivateVisibleProperty =
AvaloniaProperty.Register<CoinListView, bool>(nameof(SelectAllNonPrivateVisible), defaultBindingMode: BindingMode.TwoWay);
public bool SelectAllNonPrivateVisible
{
get => GetValue(SelectAllNonPrivateVisibleProperty);
set => SetValue(SelectAllNonPrivateVisibleProperty, value);
}
public CoinListView()
{
InitializeComponent();
SelectAllNonPrivateVisible = true;
this.WhenAnyValue(x => x.DataContext)
.Subscribe(dataContext =>
{
if (dataContext is CoinListViewModel viewmodel)
{
viewmodel.SelectAllNonPrivateVisible = SelectAllNonPrivateVisible;
}
});
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
```
Add binding mode and comment. | ```c#
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Markup.Xaml;
using ReactiveUI;
using System;
using System.Reactive.Linq;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class CoinListView : UserControl
{
public static readonly StyledProperty<bool> SelectAllNonPrivateVisibleProperty =
AvaloniaProperty.Register<CoinListView, bool>(nameof(SelectAllNonPrivateVisible), defaultBindingMode: BindingMode.OneWayToSource);
public bool SelectAllNonPrivateVisible
{
get => GetValue(SelectAllNonPrivateVisibleProperty);
set => SetValue(SelectAllNonPrivateVisibleProperty, value);
}
public CoinListView()
{
InitializeComponent();
SelectAllNonPrivateVisible = true;
this.WhenAnyValue(x => x.DataContext)
.Subscribe(dataContext =>
{
if (dataContext is CoinListViewModel viewmodel)
{
// Value is only propagated when DataContext is set at the beginning.
viewmodel.SelectAllNonPrivateVisible = SelectAllNonPrivateVisible;
}
});
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
``` |
37f830bc-7dfe-4b6f-a81d-3a40d094e6f2 | {
"language": "C#"
} | ```c#
@using Site.App_Code
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
Layout = "SW_Master.cshtml";
}
<div class="clearfix">
@Html.Partial("LeftNavigation",@Model.Content)
<div class="" style="float: left;width: 75%;padding-left: 30px;">
<h3>
@Model.Content.GetTitleOrName()
</h3>
<p>
@Convert.ToDateTime(Model.Content.UpdateDate).ToString("D")
</p>
<p>
@Html.Raw(Model.Content.GetPropertyValue<string>("bodyText"))
</p>
</div>
@Html.Partial("ContentPanels",@Model.Content)
</div>
```
Remove title and date from product item page | ```c#
@using Site.App_Code
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
Layout = "SW_Master.cshtml";
}
<div class="clearfix">
@Html.Partial("LeftNavigation",@Model.Content)
<div class="" style="float: left;width: 75%;padding-left: 30px;">
@*<h3>
@Model.Content.GetTitleOrName()
</h3>
<p>
@Convert.ToDateTime(Model.Content.UpdateDate).ToString("D")
</p>*@
<p>
@Html.Raw(Model.Content.GetPropertyValue<string>("bodyText"))
</p>
</div>
@Html.Partial("ContentPanels",@Model.Content)
</div>
``` |
a2bc6a65-285b-4241-89cd-5240a7b4f523 | {
"language": "C#"
} | ```c#
#if DNX451
using System;
using System.IO;
namespace BuildSpritesheet {
class Program {
static void Main(string[] args) {
PrepareOutputDirectory();
SpritePreparer.PrepareSprites();
Console.WriteLine();
Console.WriteLine("Done processing individual files");
Console.WriteLine();
SpritesheetBuilder.BuildSpritesheet();
Console.WriteLine();
Console.WriteLine("Done building spritesheet");
Console.ReadKey();
}
private static void PrepareOutputDirectory() {
Directory.CreateDirectory(Config.WwwRootSkillsPath);
var outputDirectory = new DirectoryInfo(Config.WwwRootSkillsPath);
outputDirectory.Empty();
}
}
}
#endif```
Add "Press any key to exit." | ```c#
#if DNX451
using System;
using System.IO;
namespace BuildSpritesheet {
class Program {
static void Main(string[] args) {
PrepareOutputDirectory();
SpritePreparer.PrepareSprites();
Console.WriteLine();
Console.WriteLine("Done processing individual files");
Console.WriteLine();
SpritesheetBuilder.BuildSpritesheet();
Console.WriteLine();
Console.WriteLine("Done building spritesheet. Press any key to exit.");
Console.ReadKey();
}
private static void PrepareOutputDirectory() {
Directory.CreateDirectory(Config.WwwRootSkillsPath);
var outputDirectory = new DirectoryInfo(Config.WwwRootSkillsPath);
outputDirectory.Empty();
}
}
}
#endif``` |
b72b853a-d34a-48d6-8685-3eedde6efcf8 | {
"language": "C#"
} | ```c#
using JetBrains.IDE.RunConfig;
namespace AlexPovar.ReSharperHelpers.Build
{
public class RunConfigProjectWithSolutionBuild : RunConfigBase
{
public override void Execute(RunConfigContext context)
{
context.ExecutionProvider.Execute(null);
}
}
}```
Hide irrelevant options from build action configuration | ```c#
using System.Windows;
using JetBrains.DataFlow;
using JetBrains.IDE.RunConfig;
using JetBrains.ProjectModel;
using JetBrains.VsIntegration.IDE.RunConfig;
namespace AlexPovar.ReSharperHelpers.Build
{
public class RunConfigProjectWithSolutionBuild : RunConfigBase
{
public override void Execute(RunConfigContext context)
{
context.ExecutionProvider.Execute(null);
}
public override IRunConfigEditorAutomation CreateEditor(Lifetime lifetime, IRunConfigCommonAutomation commonEditor, ISolution solution)
{
//Configure commot editor to hide build options. We support solution build only.
commonEditor.IsWholeSolutionChecked.Value = true;
commonEditor.WholeSolutionVisibility.Value = Visibility.Collapsed;
commonEditor.IsSpecificProjectChecked.Value = false;
var casted = commonEditor as RunConfigCommonAutomation;
if (casted != null)
{
casted.ProjectRequiredVisibility.Value = Visibility.Collapsed;
}
return null;
}
}
}``` |
d6820333-8985-4696-9993-a178f668df5c | {
"language": "C#"
} | ```c#
using System;
namespace FbxSharp
{
public class AnimStack : Collection
{
#region Public Attributes
public readonly PropertyT<string> Description = new PropertyT<string>( "Description");
public readonly PropertyT<FbxTime> LocalStart = new PropertyT<FbxTime>("LocalStart");
public readonly PropertyT<FbxTime> LocalStop = new PropertyT<FbxTime>("LocalStop");
public readonly PropertyT<FbxTime> ReferenceStart = new PropertyT<FbxTime>("ReferenceStart");
public readonly PropertyT<FbxTime> ReferenceStop = new PropertyT<FbxTime>("ReferenceStop");
#endregion
#region Utility functions.
public FbxTimeSpan GetLocalTimeSpan()
{
return new FbxTimeSpan(LocalStart.Get(), LocalStop.Get());
}
public void SetLocalTimeSpan(FbxTimeSpan pTimeSpan)
{
LocalStart.Set(pTimeSpan.GetStart());
LocalStop.Set(pTimeSpan.GetStop());
}
public FbxTimeSpan GetReferenceTimeSpan()
{
throw new NotImplementedException();
}
public void SetReferenceTimeSpan(FbxTimeSpan pTimeSpan)
{
throw new NotImplementedException();
}
public bool BakeLayers(AnimEvaluator pEvaluator, FbxTime pStart, FbxTime pStop, FbxTime pPeriod)
{
throw new NotImplementedException();
}
#endregion
}
}
```
Add the built-in properties to the Properties collection. | ```c#
using System;
namespace FbxSharp
{
public class AnimStack : Collection
{
public AnimStack(String name="")
: base(name)
{
Properties.Add(Description);
Properties.Add(LocalStart);
Properties.Add(LocalStop);
Properties.Add(ReferenceStart);
Properties.Add(ReferenceStop);
}
#region Public Attributes
public readonly PropertyT<string> Description = new PropertyT<string>( "Description");
public readonly PropertyT<FbxTime> LocalStart = new PropertyT<FbxTime>("LocalStart");
public readonly PropertyT<FbxTime> LocalStop = new PropertyT<FbxTime>("LocalStop");
public readonly PropertyT<FbxTime> ReferenceStart = new PropertyT<FbxTime>("ReferenceStart");
public readonly PropertyT<FbxTime> ReferenceStop = new PropertyT<FbxTime>("ReferenceStop");
#endregion
#region Utility functions.
public FbxTimeSpan GetLocalTimeSpan()
{
return new FbxTimeSpan(LocalStart.Get(), LocalStop.Get());
}
public void SetLocalTimeSpan(FbxTimeSpan pTimeSpan)
{
LocalStart.Set(pTimeSpan.GetStart());
LocalStop.Set(pTimeSpan.GetStop());
}
public FbxTimeSpan GetReferenceTimeSpan()
{
throw new NotImplementedException();
}
public void SetReferenceTimeSpan(FbxTimeSpan pTimeSpan)
{
throw new NotImplementedException();
}
public bool BakeLayers(AnimEvaluator pEvaluator, FbxTime pStart, FbxTime pStop, FbxTime pPeriod)
{
throw new NotImplementedException();
}
#endregion
}
}
``` |
e4223e6c-109d-4f76-bb93-9cd70587989e | {
"language": "C#"
} | ```c#
@model IFS.Web.Core.Upload.UploadedFile
@{
ViewBag.Title = $"Upload complete: {Model.Metadata.OriginalFileName}";
}
<h2>@ViewBag.Title</h2>
<div class="alert alert-success">
The upload of your file has completed: <code>@Model.Metadata.OriginalFileName</code>.
</div>
@{
string downloadLink = this.Url.RouteUrl("DownloadFile", new {id = Model.Id}, this.Context.Request.Scheme);
}
<p>
Download link to share: <input type="text" value="@downloadLink" class="form-control" readonly="readonly"/>
</p>
<p>
Test link: <a href="@downloadLink">@downloadLink</a>
</p>
<p>
<a asp-action="Index" class="btn btn-primary">Upload another file</a>
</p>```
Replace URL in address bar for easy copying | ```c#
@using System.Text.Encodings.Web
@model IFS.Web.Core.Upload.UploadedFile
@{
ViewBag.Title = $"Upload complete: {Model.Metadata.OriginalFileName}";
}
<h2>@ViewBag.Title</h2>
<div class="alert alert-success">
The upload of your file has completed: <code>@Model.Metadata.OriginalFileName</code>.
</div>
@{
string downloadLink = this.Url.RouteUrl("DownloadFile", new {id = Model.Id}, this.Context.Request.Scheme);
}
<p>
Download link to share: <input type="text" value="@downloadLink" class="form-control" readonly="readonly"/>
</p>
<p>
Test link: <a href="@downloadLink">@downloadLink</a>
</p>
<p>
<a asp-action="Index" class="btn btn-primary">Upload another file</a>
</p>
@section scripts {
<script>
(function() {
// Replace URL for easy copying
if ('replaceState' in history) {
history.replaceState({}, null, '@JavaScriptEncoder.Default.Encode(downloadLink)');
}
})();
</script>
}``` |
76f2aebc-f51d-4a8b-9017-f6b9fc3e3355 | {
"language": "C#"
} | ```c#
@using Aliencube.ReCaptcha.Wrapper.Mvc
@model Aliencube.ReCaptcha.Wrapper.WebApp.Models.HomeIndexViewModel
@{
ViewBag.Title = "Index";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm(MVC.Home.ActionNames.Index, MVC.Home.Name, FormMethod.Post))
{
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new Dictionary<string, object>() {{"class", "form-control"}})
</div>
@Html.ReCaptcha(new Dictionary<string, object>() { { "class", "form-group" }, { "data-sitekey", Model.SiteKey } })
<input class="btn btn-default" type="submit" name="Submit" />
}
@if (IsPost)
{
<div>
<ul>
<li>Success: @Model.Success</li>
@if (@Model.ErrorCodes != null && @Model.ErrorCodes.Any())
{
<li>
ErrorCodes:
<ul>
@foreach (var errorCode in Model.ErrorCodes)
{
<li>@errorCode</li>
}
</ul>
</li>
}
<li>ErorCodes: @Model.ErrorCodes</li>
</ul>
</div>
}
@section Scripts
{
@Html.ReCaptchaApiJs(new Dictionary<string, object>() { { "src", Model.ApiUrl } })
}
```
Update reCaptcha API js rendering script | ```c#
@using Aliencube.ReCaptcha.Wrapper.Mvc
@model Aliencube.ReCaptcha.Wrapper.WebApp.Models.HomeIndexViewModel
@{
ViewBag.Title = "Index";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm(MVC.Home.ActionNames.Index, MVC.Home.Name, FormMethod.Post))
{
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new Dictionary<string, object>() {{"class", "form-control"}})
</div>
@Html.ReCaptcha(new Dictionary<string, object>() { { "class", "form-group" }, { "data-sitekey", Model.SiteKey } })
<input class="btn btn-default" type="submit" name="Submit" />
}
@if (IsPost)
{
<div>
<ul>
<li>Success: @Model.Success</li>
@if (@Model.ErrorCodes != null && @Model.ErrorCodes.Any())
{
<li>
ErrorCodes:
<ul>
@foreach (var errorCode in Model.ErrorCodes)
{
<li>@errorCode</li>
}
</ul>
</li>
}
<li>ErorCodes: @Model.ErrorCodes</li>
</ul>
</div>
}
@section Scripts
{
@Html.ReCaptchaApiJs(Model.ApiUrl, JsRenderingOptions.Async | JsRenderingOptions.Defer)
}
``` |
e2809274-c750-4589-bb82-95e68a4c0cea | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Html2Markdown")]
[assembly: AssemblyDescription("A library for converting HTML to markdown syntax in C#")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Simon Baynes")]
[assembly: AssemblyProduct("Html2Markdown")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("daf67b0f-5a0c-4789-ac19-799160a5e038")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.2.*")]
```
Increase move the version number to 2.1.3 | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Html2Markdown")]
[assembly: AssemblyDescription("A library for converting HTML to markdown syntax in C#")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Simon Baynes")]
[assembly: AssemblyProduct("Html2Markdown")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("daf67b0f-5a0c-4789-ac19-799160a5e038")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.3.*")]
``` |
39a15b78-bf4e-4ce7-85ef-a64b39fae375 | {
"language": "C#"
} | ```c#
using System.Numerics;
namespace DynamixelServo.Quadruped
{
public static class Vector3Extensions
{
public static Vector3 Normal(this Vector3 vector)
{
float len = vector.Length();
return new Vector3(vector.X / len, vector.Y / len, vector.Z / len);
}
public static bool Similar(this Vector3 a, Vector3 b, float marginOfError = float.Epsilon)
{
return Vector3.Distance(a, b) <= marginOfError;
}
}
}
```
Update normalize extension method to use the built in hardware accelerated static method | ```c#
using System.Numerics;
namespace DynamixelServo.Quadruped
{
public static class Vector3Extensions
{
public static Vector3 Normal(this Vector3 vector)
{
return Vector3.Normalize(vector);
}
public static bool Similar(this Vector3 a, Vector3 b, float marginOfError = float.Epsilon)
{
return Vector3.Distance(a, b) <= marginOfError;
}
}
}
``` |
082b3bef-c01f-4c64-a1d3-6fd17ddf2ce7 | {
"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.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Organizing;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Organizing;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Organizing
{
public abstract class AbstractOrganizerTests
{
protected void Check(string initial, string final)
{
CheckResult(initial, final);
CheckResult(initial, final, Options.Script);
}
protected void Check(string initial, string final, bool specialCaseSystem)
{
CheckResult(initial, final, specialCaseSystem);
CheckResult(initial, final, specialCaseSystem, Options.Script);
}
protected void CheckResult(string initial, string final, bool specialCaseSystem, CSharpParseOptions options = null)
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(initial))
{
var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
var newRoot = OrganizingService.OrganizeAsync(document).Result.GetSyntaxRootAsync().Result;
Assert.Equal(final, newRoot.ToFullString());
}
}
protected void CheckResult(string initial, string final, CSharpParseOptions options = null)
{
CheckResult(initial, final, false, options);
}
}
}
```
Test Fixup for a Line Normalization Issue. | ```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.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Organizing;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Organizing;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Organizing
{
public abstract class AbstractOrganizerTests
{
protected void Check(string initial, string final)
{
CheckResult(initial, final);
CheckResult(initial, final, Options.Script);
}
protected void Check(string initial, string final, bool specialCaseSystem)
{
CheckResult(initial, final, specialCaseSystem);
CheckResult(initial, final, specialCaseSystem, Options.Script);
}
protected void CheckResult(string initial, string final, bool specialCaseSystem, CSharpParseOptions options = null)
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(initial))
{
var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
var newRoot = OrganizingService.OrganizeAsync(document).Result.GetSyntaxRootAsync().Result;
Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString());
}
}
protected void CheckResult(string initial, string final, CSharpParseOptions options = null)
{
CheckResult(initial, final, false, options);
}
}
}
``` |
bc6d6700-d989-49cf-b61c-90f42b5134b3 | {
"language": "C#"
} | ```c#
using Microsoft.Build.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace Microsoft.DotNet.Build.Tasks
{
public class UpdatePackageDependencyVersion : VisitProjectDependencies
{
[Required]
public string PackageId { get; set; }
[Required]
public string OldVersion { get; set; }
[Required]
public string NewVersion { get; set; }
public override bool VisitPackage(JProperty package, string projectJsonPath)
{
var dependencyIdentifier = package.Name;
string dependencyVersion;
if (package.Value is JObject)
{
dependencyVersion = package.Value["version"].Value<string>();
}
else if (package.Value is JValue)
{
dependencyVersion = package.Value.ToObject<string>();
}
else
{
throw new ArgumentException(string.Format(
"Unrecognized dependency element for {0} in {1}",
package.Name,
projectJsonPath));
}
if (dependencyIdentifier == PackageId && dependencyVersion == OldVersion)
{
Log.LogMessage(
"Changing {0} {1} to {2} in {3}",
dependencyIdentifier,
dependencyVersion,
NewVersion,
projectJsonPath);
if (package.Value is JObject)
{
package.Value["version"] = NewVersion;
}
else
{
package.Value = NewVersion;
}
return true;
}
return false;
}
}
}
```
Remove requirement for dependency nodes to have a version. | ```c#
using Microsoft.Build.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace Microsoft.DotNet.Build.Tasks
{
public class UpdatePackageDependencyVersion : VisitProjectDependencies
{
[Required]
public string PackageId { get; set; }
[Required]
public string OldVersion { get; set; }
[Required]
public string NewVersion { get; set; }
public override bool VisitPackage(JProperty package, string projectJsonPath)
{
var dependencyIdentifier = package.Name;
string dependencyVersion;
if (package.Value is JObject)
{
dependencyVersion = package.Value["version"]?.Value<string>();
}
else if (package.Value is JValue)
{
dependencyVersion = package.Value.ToObject<string>();
}
else
{
throw new ArgumentException(string.Format(
"Unrecognized dependency element for {0} in {1}",
package.Name,
projectJsonPath));
}
if (dependencyVersion == null)
{
return false;
}
if (dependencyIdentifier == PackageId && dependencyVersion == OldVersion)
{
Log.LogMessage(
"Changing {0} {1} to {2} in {3}",
dependencyIdentifier,
dependencyVersion,
NewVersion,
projectJsonPath);
if (package.Value is JObject)
{
package.Value["version"] = NewVersion;
}
else
{
package.Value = NewVersion;
}
return true;
}
return false;
}
}
}
``` |
869723dc-ed6d-42c9-b9e7-8bc50767d650 | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace RedditSharp
{
public class CreatedThing : Thing
{
private Reddit Reddit { get; set; }
public CreatedThing(Reddit reddit, JToken json) : base(json)
{
Reddit = reddit;
JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings);
}
[JsonProperty("created")]
[JsonConverter(typeof(UnixTimestampConverter))]
public DateTime Created { get; set; }
}
}
```
Add CreatedUTC to Created Thing | ```c#
using System;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace RedditSharp
{
public class CreatedThing : Thing
{
private Reddit Reddit { get; set; }
public CreatedThing(Reddit reddit, JToken json) : base(json)
{
Reddit = reddit;
JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings);
}
[JsonProperty("created")]
[JsonConverter(typeof(UnixTimestampConverter))]
public DateTime Created { get; set; }
[JsonProperty("created_utc")]
[JsonConverter(typeof(UnixTimestampConverter))]
public DateTime CreatedUTC { get; set; }
}
}
``` |
03e1c820-2758-4062-a83c-3c002c0bcd0d | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class AttackBuilding : MonoBehaviour
{
BuildingProperties properties;
SphereCollider collider;
void Start () {
properties = GetComponent<BuildingProperties> ();
collider = gameObject.AddComponent<SphereCollider> ();
collider.isTrigger = true;
collider.radius = properties.radius;
}
void OnTriggerEnter (Collider col) {
// TODO: target enemy
}
}
```
Refactor collider name for attack behaviour | ```c#
using UnityEngine;
using System.Collections;
public class AttackBuilding : MonoBehaviour
{
BuildingProperties properties;
SphereCollider attackZone;
void Start () {
properties = GetComponent<BuildingProperties> ();
attackZone = gameObject.AddComponent<SphereCollider> ();
attackZone.isTrigger = true;
attackZone.radius = properties.radius;
}
void OnTriggerEnter (Collider col) {
// TODO: target enemy
}
}
``` |
0f58abec-a092-46a5-a558-07261c6aa311 | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MapperTestsForDocString.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using NFluent;
using NUnit.Framework;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.Test.ObjectModel
{
[TestFixture]
public class MapperTestsForDocString
{
[Test]
public void MapToStringDocString_NullArgument_ReturnsNull()
{
var mapper = CreateMapper();
string docString = mapper.MapToString((Gherkin3.Ast.DocString) null);
Check.That(docString).IsNull();
}
private static Mapper CreateMapper()
{
return FactoryMethods.CreateMapper();
}
}
}```
Add namespace alias for Gherkin3.Ast | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MapperTestsForDocString.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using NFluent;
using NUnit.Framework;
using PicklesDoc.Pickles.ObjectModel;
using G = Gherkin3.Ast;
namespace PicklesDoc.Pickles.Test.ObjectModel
{
[TestFixture]
public class MapperTestsForDocString
{
[Test]
public void MapToStringDocString_NullArgument_ReturnsNull()
{
var mapper = CreateMapper();
string docString = mapper.MapToString((G.DocString) null);
Check.That(docString).IsNull();
}
private static Mapper CreateMapper()
{
return FactoryMethods.CreateMapper();
}
}
}``` |
e2b5ca4d-1b91-4a1a-9a52-b189f152a1bf | {
"language": "C#"
} | ```c#
namespace ShellHookLauncher
{
internal static partial class ShellHookHelper
{
public const string DllFileName = "ShellHook64.dll";
public const string PanelessNamedPipe = "PanelessHookId64-5b4f1ea2-c775-11e2-8888-47c85008ead5";
}
}
```
Fix up 32 bit constants. | ```c#
namespace ShellHookLauncher
{
internal static partial class ShellHookHelper
{
public const string DllFileName = "ShellHook32.dll";
public const string PanelessNamedPipe = "PanelessHookId32-5b4f1ea2-c775-11e2-8888-47c85008ead5";
}
}
``` |
95932ee4-e9a2-40d2-b3e4-54ea2c34f389 | {
"language": "C#"
} | ```c#
using PerplexUmbraco.Forms.Code.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using static PerplexUmbraco.Forms.Code.Constants;
using Umbraco.Forms.Core;
namespace PerplexUmbraco.Forms.FieldTypes
{
public class PerplexImageUpload : PerplexBaseFileFieldType
{
protected override PerplexBaseFileConfig Config => PerplexUmbracoFormsConfig.Get.PerplexImageUpload;
public PerplexImageUpload()
{
Id = new Guid("11fff56b-7e0e-4bfc-97ba-b5126158d33d");
Name = "Perplex image upload";
FieldTypeViewName = $"FieldType.{ nameof(PerplexImageUpload) }.cshtml";
Description = "Renders an upload field";
Icon = "icon-download-alt";
DataType = FieldDataType.String;
SortOrder = 10;
Category = "Simple";
}
}
}```
Fix for missing multiple image uploads checkbox on image upload field type. | ```c#
using PerplexUmbraco.Forms.Code.Configuration;
using System;
using System.Collections.Generic;
using Umbraco.Forms.Core;
using Umbraco.Forms.Core.Attributes;
namespace PerplexUmbraco.Forms.FieldTypes
{
public class PerplexImageUpload : PerplexBaseFileFieldType
{
protected override PerplexBaseFileConfig Config => PerplexUmbracoFormsConfig.Get.PerplexImageUpload;
public PerplexImageUpload()
{
Id = new Guid("11fff56b-7e0e-4bfc-97ba-b5126158d33d");
Name = "Perplex image upload";
FieldTypeViewName = $"FieldType.{ nameof(PerplexImageUpload) }.cshtml";
Description = "Renders an upload field";
Icon = "icon-download-alt";
DataType = FieldDataType.String;
SortOrder = 10;
Category = "Simple";
}
public override Dictionary<string, Setting> Settings()
{
Dictionary<string, Setting> settings = base.Settings() ?? new Dictionary<string, Setting>();
settings.Add("MultiUpload", new Setting("Multi upload")
{
description = "If checked, allows the user to upload multiple files",
view = "checkbox"
});
return settings;
}
}
}``` |
c5d69703-2152-451f-9d9b-6e96f511736e | {
"language": "C#"
} | ```c#
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
long sum = ParallelEnumerable.Range(3, max - 3)
.Where((p) => p % 2 != 0)
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
Answer = sum + 2;
return 0;
}
}
}
```
Remove special case for odd numbers | ```c#
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
long sum = ParallelEnumerable.Range(3, max - 3)
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
Answer = sum + 2;
return 0;
}
}
}
``` |
162b416d-f011-436d-88bf-b9de05442c78 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0")]
```
Revert to fixed versioning scheme used by build | ```c#
using System.Reflection;
// These "special" version numbers are found and replaced at build time.
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.1.1.1")]
[assembly: AssemblyInformationalVersion("1.0.0")]
``` |
1274c45f-b02a-4cf1-aea0-8ca187a1a5be | {
"language": "C#"
} | ```c#
using Jasper.Util;
using TestingSupport.Compliance;
using Xunit;
namespace Jasper.Testing.Transports.Tcp
{
public class Sender : JasperOptions
{
public Sender()
{
Endpoints.ListenForMessagesFrom($"tcp://localhost:2289/incoming".ToUri());
}
}
public class Receiver : JasperOptions
{
public Receiver()
{
Endpoints.ListenForMessagesFrom($"tcp://localhost:2288/incoming".ToUri());
}
}
[Collection("compliance")]
public class LightweightTcpTransportCompliance : SendingCompliance
{
public LightweightTcpTransportCompliance() : base($"tcp://localhost:2288/incoming".ToUri())
{
SenderIs<Sender>();
ReceiverIs<Receiver>();
}
}
}
```
Allow passing port number to test setup | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Jasper.Util;
using TestingSupport.Compliance;
using Xunit;
namespace Jasper.Testing.Transports.Tcp
{
public class Sender : JasperOptions
{
public Sender(int portNumber)
{
Endpoints.ListenForMessagesFrom($"tcp://localhost:{portNumber}/incoming".ToUri());
}
public Sender()
: this(2389)
{
}
}
public class Receiver : JasperOptions
{
public Receiver(int portNumber)
{
Endpoints.ListenForMessagesFrom($"tcp://localhost:{portNumber}/incoming".ToUri());
}
public Receiver() : this(2388)
{
}
}
public class PortFinder
{
private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0);
public static int GetAvailablePort()
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(DefaultLoopbackEndpoint);
var port = ((IPEndPoint)socket.LocalEndPoint).Port;
return port;
}
}
[Collection("compliance")]
public class LightweightTcpTransportCompliance : SendingCompliance
{
public LightweightTcpTransportCompliance() : base($"tcp://localhost:{PortFinder.GetAvailablePort()}/incoming".ToUri())
{
SenderIs(new Sender(PortFinder.GetAvailablePort()));
ReceiverIs(new Receiver(theOutboundAddress.Port));
}
}
}
``` |
b3bd70b9-cdfc-4db5-87b4-ed9d2c3349a1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Testity.EngineComponents;
namespace Testity.EngineComponents.Unity3D
{
public interface ITestityBehaviour<out TScriptComponentType> : ITestityBehaviour
where TScriptComponentType : EngineScriptComponent
{
TScriptComponentType ScriptComponent { get; }
}
public interface ITestityBehaviour
{
void Initialize();
}
}
```
Add Untyped Getter for EngineScriptComponent | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Testity.EngineComponents;
namespace Testity.EngineComponents.Unity3D
{
public interface ITestityBehaviour<out TScriptComponentType> : ITestityBehaviour
where TScriptComponentType : EngineScriptComponent
{
TScriptComponentType ScriptComponent { get; }
}
public interface ITestityBehaviour
{
void Initialize();
object GetUntypedScriptComponent { get; }
}
}
``` |
c424b451-4314-4368-a1b8-3c4c0d0cb8e6 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using log4net;
namespace SharpArchContrib.Data.NHibernate {
[Serializable]
public abstract class TransactionManagerBase : ITransactionManager {
private static readonly ILog logger = LogManager.GetLogger(typeof(TransactionManagerBase));
private static int transactionDepth;
#region ITransactionManager Members
public int TransactionDepth {
get { return transactionDepth; }
}
public virtual object PushTransaction(string factoryKey, object transactionState) {
Interlocked.Increment(ref transactionDepth);
Log(string.Format("Push Transaction to Depth {0}", transactionDepth));
return transactionState;
}
public abstract bool TransactionIsActive(string factoryKey);
public virtual object PopTransaction(string factoryKey, object transactionState) {
Interlocked.Decrement(ref transactionDepth);
Log(string.Format("Pop Transaction to Depth {0}", transactionDepth));
return transactionState;
}
public abstract object RollbackTransaction(string factoryKey, object transactionState);
public abstract object CommitTransaction(string factoryKey, object transactionState);
public abstract string Name { get; }
#endregion
protected void Log(string message) {
logger.Debug(string.Format("{0}: {1}", Name, message));
}
}
}```
Fix thread safety issue in TransactionManager. The depth should be per-thread. | ```c#
using System;
using System.Threading;
using log4net;
namespace SharpArchContrib.Data.NHibernate {
[Serializable]
public abstract class TransactionManagerBase : ITransactionManager {
private static readonly ILog logger = LogManager.GetLogger(typeof(TransactionManagerBase));
[ThreadStatic]
private static int transactionDepth;
#region ITransactionManager Members
public int TransactionDepth {
get { return transactionDepth; }
}
public virtual object PushTransaction(string factoryKey, object transactionState) {
Interlocked.Increment(ref transactionDepth);
Log(string.Format("Push Transaction to Depth {0}", transactionDepth));
return transactionState;
}
public abstract bool TransactionIsActive(string factoryKey);
public virtual object PopTransaction(string factoryKey, object transactionState) {
Interlocked.Decrement(ref transactionDepth);
Log(string.Format("Pop Transaction to Depth {0}", transactionDepth));
return transactionState;
}
public abstract object RollbackTransaction(string factoryKey, object transactionState);
public abstract object CommitTransaction(string factoryKey, object transactionState);
public abstract string Name { get; }
#endregion
protected void Log(string message) {
logger.Debug(string.Format("{0}: {1}", Name, message));
}
}
}``` |
d48b5523-fb47-4a4c-95ff-1947f91f91b4 | {
"language": "C#"
} | ```c#
using Microsoft.Data.Sqlite;
using System.Collections.Generic;
namespace Business.Core.SQLite
{
public class Command : ICommand
{
IReader Reader { get; set; }
public SqliteConnection SQLiteConnection { get; set; }
public SqliteCommand SQLiteCommand { get; set; }
public SqliteDataReader SQLiteReader { get; set; }
public List<Parameter> Parameters { get; set; }
public Command() {
SQLiteCommand = new SqliteCommand();
Parameters = new List<Parameter>();
}
public string CommandText {
get {
return SQLiteCommand?.CommandText;
}
set {
SQLiteCommand.CommandText = value;
}
}
public IReader ExecuteReader() {
SQLiteCommand.Connection = SQLiteConnection;
foreach(var parameter in Parameters) {
SQLiteCommand.Parameters.Add(new SqliteParameter(parameter.Name, parameter.Value));
}
SQLiteReader = SQLiteCommand.ExecuteReader();
Reader = new Reader() { SQLiteReader = SQLiteReader };
return Reader;
}
public object ExecuteScalar() {
throw new System.NotImplementedException();
}
}
}
```
Refactor and add ExecuteScalar to SQLite wrapper | ```c#
using Microsoft.Data.Sqlite;
using System.Collections.Generic;
namespace Business.Core.SQLite
{
public class Command : ICommand
{
IReader Reader { get; set; }
public SqliteConnection SQLiteConnection { get; set; }
public SqliteCommand SQLiteCommand { get; set; }
public SqliteDataReader SQLiteReader { get; set; }
public List<Parameter> Parameters { get; set; }
public Command() {
SQLiteCommand = new SqliteCommand();
Parameters = new List<Parameter>();
}
public string CommandText {
get {
return SQLiteCommand?.CommandText;
}
set {
SQLiteCommand.CommandText = value;
}
}
public IReader ExecuteReader() {
MakeReady();
SQLiteReader = SQLiteCommand.ExecuteReader();
Reader = new Reader() { SQLiteReader = SQLiteReader };
return Reader;
}
public object ExecuteScalar() {
MakeReady();
return SQLiteCommand.ExecuteScalar();
}
private void MakeReady() {
SQLiteCommand.Connection = SQLiteConnection;
foreach (var parameter in Parameters) {
SQLiteCommand.Parameters.Add(new SqliteParameter(parameter.Name, parameter.Value));
}
}
}
}
``` |
6d53d1d2-bb5d-4f0e-947f-39652f5e8229 | {
"language": "C#"
} | ```c#
@page
@model RazorPagesWebSite.HelloWorldWithPageModelHandler
Hello, @Model.Message!
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
}```
Make test of @page/@model whitespace | ```c#
@page
@model RazorPagesWebSite.HelloWorldWithPageModelHandler
Hello, @Model.Message!
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
}``` |
420203e9-4070-4c33-8ebd-33cdd76e3a3d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace Rawr.LaunchPad.Installer
{
public class RegistryEditor
{
readonly string targetPath;
readonly List<string> keyNames = new List<string>
{
"Excel.CSV",
"Excel.Sheet.8",
"Excel.Macrosheet",
"Excel.SheetBinaryMacroEnabled.12",
"Excel.Addin",
"Excel.AddInMacroEnabled",
"Excel.SheetMacroEnabled.12",
"Excel.Sheet.12",
"Excel.Template.8",
};
public RegistryEditor(string targetPath)
{
this.targetPath = targetPath;
}
public void AddEntries()
{
foreach (var name in keyNames)
{
using (var registryKey = Registry.ClassesRoot.OpenSubKey(name, true))
{
var shell = registryKey.CreateSubKey("shell");
var newWindow = shell.CreateSubKey("Open in new window");
var command = newWindow.CreateSubKey("command");
command.SetValue(null, $"{targetPath} -f \"%1\"");
}
}
}
}
}
```
Remove registry entries on uninstall + refactor | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace Rawr.LaunchPad.Installer
{
public class RegistryEditor
{
readonly List<string> keyNames = new List<string>
{
"Excel.CSV",
"Excel.Sheet.8",
"Excel.Macrosheet",
"Excel.SheetBinaryMacroEnabled.12",
"Excel.Addin",
"Excel.AddInMacroEnabled",
"Excel.SheetMacroEnabled.12",
"Excel.Sheet.12",
"Excel.Template.8",
};
public void AddEntries(string targetPath)
{
foreach (var name in keyNames.Take(1))
{
using (var registryKey = Registry.ClassesRoot.OpenSubKey(name, true))
using (var shell = registryKey?.CreateSubKey("shell"))
using (var newWindow = shell?.CreateSubKey("Open in new window"))
using (var command = newWindow?.CreateSubKey("command"))
{
if (command == null)
throw new InvalidOperationException($"Unable to set key for '{name}'. Command subkey returned as null. This is likely a permissions issue.");
command.SetValue(null, $"{targetPath} -f \"%1\"");
}
}
}
public void RemoveEntries()
{
foreach (var name in keyNames.Take(1))
{
using (var registryKey = Registry.ClassesRoot.OpenSubKey(name, true))
using (var shell = registryKey?.OpenSubKey("shell", true))
{
if (shell == null)
continue;
try
{
// Assumption: the key simply doesn't exist
shell.DeleteSubKey("Open in new window");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
}
}
``` |
3e7e6380-2cd9-4ace-946f-e8137fcb63e0 | {
"language": "C#"
} | ```c#
@{
ViewData["Title"] = "Access Denied";
}
<div class="container">
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">Authentication Failed.</h2>
<p>
You have denied Competition Platform access to your resources.
</p>
</div>```
Change authentication failed error message. | ```c#
@{
ViewData["Title"] = "Access Denied";
}
<div class="container">
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">Authentication Failed.</h2>
<p>
There was a remote failure during Authentication.
</p>
</div>``` |
f4febf3d-39d4-4452-b700-53cf383d6f77 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
#if EXTENJECT_INCLUDE_ADDRESSABLE_BINDINGS
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.AddressableAssets;
#endif
namespace Zenject
{
[NoReflectionBaking]
public class AsyncFromBinderGeneric<TContract, TConcrete> : AsyncFromBinderBase where TConcrete : TContract
{
public AsyncFromBinderGeneric(
DiContainer container, BindInfo bindInfo,
BindStatement bindStatement)
: base(container, typeof(TContract), bindInfo)
{
BindStatement = bindStatement;
}
protected BindStatement BindStatement
{
get; private set;
}
protected IBindingFinalizer SubFinalizer
{
set { BindStatement.SetFinalizer(value); }
}
public AsyncFromBinderBase FromMethod(Func<Task<TConcrete>> method)
{
BindInfo.RequireExplicitScope = false;
// Don't know how it's created so can't assume here that it violates AsSingle
BindInfo.MarkAsCreationBinding = false;
SubFinalizer = new ScopableBindingFinalizer(
BindInfo,
(container, originalType) => new AsyncMethodProviderSimple<TContract, TConcrete>(method));
return this;
}
}
}```
Add cancel token variant for FromMethod | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Zenject
{
[NoReflectionBaking]
public class AsyncFromBinderGeneric<TContract, TConcrete> : AsyncFromBinderBase where TConcrete : TContract
{
public AsyncFromBinderGeneric(
DiContainer container, BindInfo bindInfo,
BindStatement bindStatement)
: base(container, typeof(TContract), bindInfo)
{
BindStatement = bindStatement;
}
protected BindStatement BindStatement
{
get; private set;
}
protected IBindingFinalizer SubFinalizer
{
set { BindStatement.SetFinalizer(value); }
}
public AsyncFromBinderBase FromMethod(Func<Task<TConcrete>> method)
{
BindInfo.RequireExplicitScope = false;
// Don't know how it's created so can't assume here that it violates AsSingle
BindInfo.MarkAsCreationBinding = false;
SubFinalizer = new ScopableBindingFinalizer(
BindInfo,
(container, originalType) => new AsyncMethodProviderSimple<TContract, TConcrete>(method));
return this;
}
public AsyncFromBinderBase FromMethod(Func<CancellationToken, Task<TConcrete>> method)
{
BindInfo.RequireExplicitScope = false;
// Don't know how it's created so can't assume here that it violates AsSingle
BindInfo.MarkAsCreationBinding = false;
SubFinalizer = new ScopableBindingFinalizer(
BindInfo,
(container, originalType) => new AsyncMethodProviderSimple<TContract, TConcrete>(method));
return this;
}
}
}``` |
8ac9acfc-dc2b-487f-8cc3-e081656c7f9b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dbticket;
namespace db_pdftest
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Invalid argument count. You must pass the path to a file.\nPress a key to exit.");
Console.ReadKey();
return;
}
TicketCheck tc_1 = new TicketCheck(args[1]);
Console.Write("Result: ");
Console.Write(String.Format("{0} of {1} points\n"), tc_1.Result, TicketCheck.MaximumScore);
Console.WriteLine("Press a key to exit.");
Console.ReadKey();
}
}
}
```
Fix for three bugs in three lines. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dbticket;
namespace db_pdftest
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Invalid argument count. You must pass the path to a file.\nPress a key to exit.");
Console.ReadKey();
return;
}
TicketCheck tc_1 = new TicketCheck(args[0]);
Console.Write("Result: ");
Console.Write(String.Format("{0} of {1} points\n", tc_1.Result, TicketCheck.MaximumScore));
Console.WriteLine("Press a key to exit.");
Console.ReadKey();
}
}
}
``` |
134152c9-3e74-4b38-82a2-11fc5b59f0c1 | {
"language": "C#"
} | ```c#
using System;
using System.Configuration;
namespace AspNet.Identity.MongoDB {
public class MongoDBIdentitySettings : ConfigurationSection {
private static MongoDBIdentitySettings settings = ConfigurationManager.GetSection("mongoDBIdentitySettings") as MongoDBIdentitySettings;
private const String userCollectionName = "userCollectionName";
private const String roleCollectionName = "roleCollectionName";
public static MongoDBIdentitySettings Settings {
get {
return settings;
}
}
//[ConfigurationProperty("frontPagePostCount", DefaultValue = 20, IsRequired = false)]
//[IntegerValidator(MinValue = 1, MaxValue = 100)]
//public int FrontPagePostCount {
// get { return (int)this["frontPagePostCount"]; }
// set { this["frontPagePostCount"] = value; }
//}
[ConfigurationProperty(userCollectionName, IsRequired = true)]
[RegexStringValidator("^[a-zA-Z]+$")]
public String UserCollectionName {
get {
return (String)this[userCollectionName];
}
set {
this[userCollectionName] = value;
}
}
[ConfigurationProperty(roleCollectionName, IsRequired = true)]
[RegexStringValidator("^[a-zA-Z]+$")]
public String RoleCollectionName {
get {
return (String)this[roleCollectionName];
}
set {
this[roleCollectionName] = value;
}
}
}
}
```
Fix issue "Unexpected RegexStringValidator failure in Configuration Property" | ```c#
using System;
using System.Configuration;
namespace AspNet.Identity.MongoDB {
public class MongoDBIdentitySettings : ConfigurationSection {
private static MongoDBIdentitySettings settings = ConfigurationManager.GetSection("mongoDBIdentitySettings") as MongoDBIdentitySettings;
private const String userCollectionName = "userCollectionName";
private const String roleCollectionName = "roleCollectionName";
public static MongoDBIdentitySettings Settings {
get {
return settings;
}
}
//[ConfigurationProperty("frontPagePostCount", DefaultValue = 20, IsRequired = false)]
//[IntegerValidator(MinValue = 1, MaxValue = 100)]
//public int FrontPagePostCount {
// get { return (int)this["frontPagePostCount"]; }
// set { this["frontPagePostCount"] = value; }
//}
[ConfigurationProperty(userCollectionName, IsRequired = true, DefaultValue = "user")]
[RegexStringValidator("^[a-zA-Z]+$")]
public String UserCollectionName {
get {
return (String)this[userCollectionName];
}
set {
this[userCollectionName] = value;
}
}
[ConfigurationProperty(roleCollectionName, IsRequired = true, DefaultValue = "role")]
[RegexStringValidator("^[a-zA-Z]+$")]
public String RoleCollectionName {
get {
return (String)this[roleCollectionName];
}
set {
this[roleCollectionName] = value;
}
}
}
}
``` |
1ba0b526-22b1-40d9-99e9-712ca776bf34 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Cognitive Services ComputerVision SDK")]
[assembly: AssemblyDescription("Provides access to the Microsoft Cognitive Services ComputerVision APIs.")]
[assembly: AssemblyVersion("3.1.0.0")]
[assembly: AssemblyFileVersion("3.1.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]```
Address AssemblyVersion issue as suggested. | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Cognitive Services ComputerVision SDK")]
[assembly: AssemblyDescription("Provides access to the Microsoft Cognitive Services ComputerVision APIs.")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.1.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
``` |
11ab1bb0-e385-4e9c-ab02-7d2d0863c0fc | {
"language": "C#"
} | ```c#
#addin "Cake.IIS"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// SETUP / TEARDOWN
///////////////////////////////////////////////////////////////////////////////
Setup(context =>
{
//Executed BEFORE the first task.
Information("Tools dir: {0}.", EnvironmentVariable("CAKE_PATHS_TOOLS"));
});
///////////////////////////////////////////////////////////////////////////////
// TASK DEFINITIONS
///////////////////////////////////////////////////////////////////////////////
Task("ApplicationPool-Create")
.Description("Create a ApplicationPool")
.Does(() =>
{
CreatePool(new ApplicationPoolSettings()
{
Name = "Test",
IdentityType = IdentityType.NetworkService
});
});
Task("Website-Create")
.Description("Create a Website")
.IsDependentOn("ApplicationPool-Create")
.Does(() =>
{
CreateWebsite(new WebsiteSettings()
{
Name = "MyBlog",
HostName = "blog.website.com",
PhysicalDirectory = "C:/Websites/Blog",
ApplicationPool = new ApplicationPoolSettings()
{
Name = "Test"
}
});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Website-Create");
///////////////////////////////////////////////////////////////////////////////
// EXECUTION
///////////////////////////////////////////////////////////////////////////////
RunTarget(target);
```
Fix issue related to task execution Website-Create. | ```c#
#addin "Cake.IIS"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// SETUP / TEARDOWN
///////////////////////////////////////////////////////////////////////////////
Setup(context =>
{
//Executed BEFORE the first task.
Information("Tools dir: {0}.", EnvironmentVariable("CAKE_PATHS_TOOLS"));
});
///////////////////////////////////////////////////////////////////////////////
// TASK DEFINITIONS
///////////////////////////////////////////////////////////////////////////////
Task("ApplicationPool-Create")
.Description("Create a ApplicationPool")
.Does(() =>
{
CreatePool(new ApplicationPoolSettings()
{
Name = "Test",
IdentityType = IdentityType.NetworkService
});
});
Task("Website-Create")
.Description("Create a Website")
.IsDependentOn("ApplicationPool-Create")
.Does(() =>
{
CreateWebsite(new WebsiteSettings()
{
Name = "MyBlog",
PhysicalDirectory = "C:/Websites/Blog",
ApplicationPool = new ApplicationPoolSettings()
{
Name = "Test"
}
});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Website-Create");
///////////////////////////////////////////////////////////////////////////////
// EXECUTION
///////////////////////////////////////////////////////////////////////////////
RunTarget(target);
``` |
c536603b-4dad-40be-9fae-7bc8b61cac78 | {
"language": "C#"
} | ```c#
using Microsoft.Extensions.Configuration;
using Nancy;
using Nancy.TinyIoc;
namespace Silverpop.Client.WebTester.Infrastructure
{
public class CustomBootstrapper : DefaultNancyBootstrapper
{
public CustomBootstrapper()
{
var builder = new ConfigurationBuilder()
.SetBasePath(RootPathProvider.GetRootPath())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.dev.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
var transactClientConfiguration = new TransactClientConfiguration();
var configuration = Configuration.GetSection("silverpop");
configuration.Bind(transactClientConfiguration);
container.Register(new TransactClient(transactClientConfiguration));
}
}
}
```
Add NancyDashboardPassword setting used to enable dashboard | ```c#
using Microsoft.Extensions.Configuration;
using Nancy;
using Nancy.Configuration;
using Nancy.Diagnostics;
using Nancy.TinyIoc;
namespace Silverpop.Client.WebTester.Infrastructure
{
public class CustomBootstrapper : DefaultNancyBootstrapper
{
public CustomBootstrapper()
{
var builder = new ConfigurationBuilder()
.SetBasePath(RootPathProvider.GetRootPath())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.dev.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public override void Configure(INancyEnvironment environment)
{
var dashboardPassword = Configuration.GetValue<string>("NancyDashboardPassword");
if (!string.IsNullOrWhiteSpace(dashboardPassword))
{
environment.Diagnostics(true, dashboardPassword);
}
base.Configure(environment);
}
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
var transactClientConfiguration = new TransactClientConfiguration();
var configuration = Configuration.GetSection("silverpop");
configuration.Bind(transactClientConfiguration);
container.Register(new TransactClient(transactClientConfiguration));
}
}
}
``` |
01b9f6c0-ba3e-4757-9fcb-dfbbec2726de | {
"language": "C#"
} | ```c#
// Any comments, input: @KevinDockx
// Any issues, requests: https://github.com/KevinDockx/HttpCacheHeaders
using Marvin.Cache.Headers;
using Marvin.Cache.Headers.Interfaces;
using Marvin.Cache.Headers.Stores;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for the HttpCache middleware (on IServiceCollection)
/// </summary>
public static class ServicesExtensions
{
public static IServiceCollection AddHttpCacheHeaders(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.Add(ServiceDescriptor.Singleton<IValidationValueStore, InMemoryValidationValueStore>());
return services;
}
}
}
```
Add overloads for configuring options when adding services | ```c#
// Any comments, input: @KevinDockx
// Any issues, requests: https://github.com/KevinDockx/HttpCacheHeaders
using Marvin.Cache.Headers;
using Marvin.Cache.Headers.Interfaces;
using Marvin.Cache.Headers.Stores;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for the HttpCache middleware (on IServiceCollection)
/// </summary>
public static class ServicesExtensions
{
public static IServiceCollection AddHttpCacheHeaders(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.Add(ServiceDescriptor.Singleton<IValidationValueStore, InMemoryValidationValueStore>());
return services;
}
public static IServiceCollection AddHttpCacheHeaders(this IServiceCollection services,
Action<ExpirationModelOptions> configureExpirationModelOptions)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configureExpirationModelOptions == null)
{
throw new ArgumentNullException(nameof(configureExpirationModelOptions));
}
services.Configure(configureExpirationModelOptions);
services.AddHttpCacheHeaders();
return services;
}
public static IServiceCollection AddHttpCacheHeaders(this IServiceCollection services,
Action<ValidationModelOptions> configureValidationModelOptions)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configureValidationModelOptions == null)
{
throw new ArgumentNullException(nameof(configureValidationModelOptions));
}
services.Configure(configureValidationModelOptions);
services.AddHttpCacheHeaders();
return services;
}
public static IServiceCollection AddHttpCacheHeaders(this IServiceCollection services,
Action<ExpirationModelOptions> configureExpirationModelOptions,
Action<ValidationModelOptions> configureValidationModelOptions)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configureExpirationModelOptions == null)
{
throw new ArgumentNullException(nameof(configureExpirationModelOptions));
}
if (configureValidationModelOptions == null)
{
throw new ArgumentNullException(nameof(configureValidationModelOptions));
}
services.Configure(configureExpirationModelOptions);
services.Configure(configureValidationModelOptions);
services.AddHttpCacheHeaders();
return services;
}
}
}
``` |
7672d504-1c44-48d2-9161-ed18224e5e1f | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal static partial class Interop
{
private static class Libraries
{
internal const string Process = "api-ms-win-core-processenvironment-l1-1-0.dll";
internal const string Console = "api-ms-win-core-console-l1-1-0.dll";
}
internal static unsafe partial class mincore
{
[DllImport("Libraries.Process")]
internal static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("Libraries.Console", EntryPoint = "WriteConsoleW")]
internal static unsafe extern bool WriteConsole(IntPtr hConsoleOutput, byte* lpBuffer, int nNumberOfCharsToWrite, out int lpNumberOfCharsWritten, IntPtr lpReservedMustBeNull);
}
}
```
Fix the name of DLL in DllImport. | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal static partial class Interop
{
private static class Libraries
{
internal const string Process = "api-ms-win-core-processenvironment-l1-1-0.dll";
internal const string Console = "api-ms-win-core-console-l1-1-0.dll";
}
internal static unsafe partial class mincore
{
[DllImport(Libraries.Process)]
internal static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport(Libraries.Console, EntryPoint = "WriteConsoleW")]
internal static unsafe extern bool WriteConsole(IntPtr hConsoleOutput, byte* lpBuffer, int nNumberOfCharsToWrite, out int lpNumberOfCharsWritten, IntPtr lpReservedMustBeNull);
}
}
``` |
6bf11706-533e-4410-bc8b-5e8b2afcfc49 | {
"language": "C#"
} | ```c#
using Arango.Client.Protocol;
namespace Arango.Client
{
public class ArangoCollectionOperation
{
private CollectionOperation _collectionOperation;
internal ArangoCollectionOperation(CollectionOperation collectionOperation)
{
_collectionOperation = collectionOperation;
}
public ArangoCollection Get(string name)
{
return _collectionOperation.Get(name);
}
public void Create(ArangoCollection collection)
{
_collectionOperation.Post(collection);
}
public bool Delete(string name)
{
return _collectionOperation.Delete(name);
}
public bool Clear(string name)
{
return _collectionOperation.PutTruncate(name);
}
}
}
```
Add xml docs to collection operations. | ```c#
using Arango.Client.Protocol;
namespace Arango.Client
{
public class ArangoCollectionOperation
{
private CollectionOperation _collectionOperation;
internal ArangoCollectionOperation(CollectionOperation collectionOperation)
{
_collectionOperation = collectionOperation;
}
/// <summary>
/// Retrieves collection object from database identified by its name.
/// </summary>
public ArangoCollection Get(string name)
{
return _collectionOperation.Get(name);
}
/// <summary>
/// Creates collection in database and assigns additional data to referenced object.
/// </summary>
public void Create(ArangoCollection collection)
{
_collectionOperation.Post(collection);
}
/// <summary>
/// Deletes specified collection from database and returnes boolean value which indicates if the operation was successful.
/// </summary>
public bool Delete(string name)
{
return _collectionOperation.Delete(name);
}
/// <summary>
/// Removes all documnets from specified collection and returns boolean values which indicates if the operation was successful.
/// </summary>
public bool Clear(string name)
{
return _collectionOperation.PutTruncate(name);
}
}
}
``` |
ed5d9514-de69-4d2f-83d2-1d3a36886476 | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace Ets.Mobile.Content.Grade
{
public sealed partial class GradeSummary : UserControl, INotifyPropertyChanged
{
public GradeSummary()
{
InitializeComponent();
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(GradeSummary), null);
public string Title
{
get { return GetValue(TitleProperty).ToString(); }
set { SetValueDp(TitleProperty, value); }
}
#region Grade
public static readonly DependencyProperty GradeProperty =
DependencyProperty.Register("Grade", typeof(string), typeof(GradeSummary), null);
public string Grade
{
get { return GetValue(GradeProperty).ToString(); }
set { SetValueDp(GradeProperty, value); }
}
#endregion
public static readonly DependencyProperty BackgroundBrushProperty =
DependencyProperty.Register("BackgroundBrush", typeof(Brush), typeof(GradeSummary), null);
public Brush BackgroundBrush
{
get { return (Brush)GetValue(BackgroundBrushProperty); }
set { SetValueDp(BackgroundBrushProperty, value); }
}
#region PropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void SetValueDp(DependencyProperty property, object value, [CallerMemberName] string propertyName = null)
{
SetValue(property, value);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}```
Remove Unecessary region in Grade Summary | ```c#
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace Ets.Mobile.Content.Grade
{
public sealed partial class GradeSummary : UserControl, INotifyPropertyChanged
{
public GradeSummary()
{
InitializeComponent();
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(GradeSummary), null);
public string Title
{
get { return GetValue(TitleProperty).ToString(); }
set { SetValueDp(TitleProperty, value); }
}
public static readonly DependencyProperty GradeProperty =
DependencyProperty.Register("Grade", typeof(string), typeof(GradeSummary), null);
public string Grade
{
get { return GetValue(GradeProperty).ToString(); }
set { SetValueDp(GradeProperty, value); }
}
public static readonly DependencyProperty BackgroundBrushProperty =
DependencyProperty.Register("BackgroundBrush", typeof(Brush), typeof(GradeSummary), null);
public Brush BackgroundBrush
{
get { return (Brush)GetValue(BackgroundBrushProperty); }
set { SetValueDp(BackgroundBrushProperty, value); }
}
#region PropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void SetValueDp(DependencyProperty property, object value, [CallerMemberName] string propertyName = null)
{
SetValue(property, value);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}``` |
022c4a60-bcd4-45cf-9afb-011ed28cf8cf | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.Numerics;
using ReactiveUI;
namespace SolidworksAddinFramework.OpenGl.Animation
{
public class LinearAnimation<T> : ReactiveObject, IAnimationSection
where T : IInterpolatable<T>
{
public T From { get; }
public T To { get; }
public TimeSpan Duration { get; }
public LinearAnimation(TimeSpan duration, T @from, T to)
{
Duration = duration;
From = @from;
To = to;
}
public Matrix4x4 Transform( TimeSpan deltaTime)
{
var beta = deltaTime.TotalMilliseconds/Duration.TotalMilliseconds;
return BlendTransform(beta);
}
public Matrix4x4 BlendTransform(double beta)
{
Debug.Assert(beta>=0 && beta<=1);
return From.Interpolate(To, beta).Transform();
}
}
public static class LinearAnimation
{
public static LinearAnimation<T> Create<T>(TimeSpan duration, T from, T to)
where T : IInterpolatable<T>
{
return new LinearAnimation<T>(duration, from, to);
}
}
}```
Remove unnecessary '@' before arg name | ```c#
using System;
using System.Diagnostics;
using System.Numerics;
using ReactiveUI;
namespace SolidworksAddinFramework.OpenGl.Animation
{
public class LinearAnimation<T> : ReactiveObject, IAnimationSection
where T : IInterpolatable<T>
{
public T From { get; }
public T To { get; }
public TimeSpan Duration { get; }
public LinearAnimation(TimeSpan duration, T from, T to)
{
Duration = duration;
From = from;
To = to;
}
public Matrix4x4 Transform( TimeSpan deltaTime)
{
var beta = deltaTime.TotalMilliseconds/Duration.TotalMilliseconds;
return BlendTransform(beta);
}
public Matrix4x4 BlendTransform(double beta)
{
Debug.Assert(beta>=0 && beta<=1);
return From.Interpolate(To, beta).Transform();
}
}
public static class LinearAnimation
{
public static LinearAnimation<T> Create<T>(TimeSpan duration, T from, T to)
where T : IInterpolatable<T>
{
return new LinearAnimation<T>(duration, from, to);
}
}
}``` |
e40ac890-78aa-42ee-a2ec-c5692796f377 | {
"language": "C#"
} | ```c#
using System;
using System.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public abstract class DbTransaction : IDbTransaction
{
private readonly IDbFactory _factory;
protected bool Disposed;
public IDbTransaction Transaction { get; set; }
public IDbConnection Connection => Transaction.Connection;
public IsolationLevel IsolationLevel => Transaction?.IsolationLevel ?? IsolationLevel.Unspecified;
protected DbTransaction(IDbFactory factory)
{
_factory = factory;
}
public void Commit()
{
if (Connection?.State == ConnectionState.Open)
{
Transaction?.Commit();
}
}
public void Rollback()
{
if (Connection?.State == ConnectionState.Open)
{
Transaction?.Rollback();
}
}
~DbTransaction()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (Disposed) return;
Disposed = true;
if (!disposing) return;
if (Transaction?.Connection == null) return;
try
{
Commit();
Transaction?.Dispose();
}
catch
{
Rollback();
throw;
}
finally
{
Transaction = null;
_factory.Release(this);
}
}
}
}
```
Add dispose for session if the session is not null. This means that the session is created with the uow | ```c#
using System;
using System.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public abstract class DbTransaction : IDbTransaction
{
private readonly IDbFactory _factory;
protected bool Disposed;
protected ISession Session;
public IDbTransaction Transaction { get; set; }
public IDbConnection Connection => Transaction.Connection;
public IsolationLevel IsolationLevel => Transaction?.IsolationLevel ?? IsolationLevel.Unspecified;
protected DbTransaction(IDbFactory factory)
{
_factory = factory;
}
public void Commit()
{
if (Connection?.State == ConnectionState.Open)
{
Transaction?.Commit();
}
}
public void Rollback()
{
if (Connection?.State == ConnectionState.Open)
{
Transaction?.Rollback();
}
}
~DbTransaction()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (Disposed) return;
Disposed = true;
if (!disposing) return;
DisposeTransaction();
DisposeSessionIfSessionIsNotNull();
}
private void DisposeTransaction()
{
if (Transaction?.Connection == null) return;
try
{
Commit();
Transaction?.Dispose();
}
catch
{
Rollback();
throw;
}
finally
{
Transaction = null;
_factory.Release(this);
}
}
private void DisposeSessionIfSessionIsNotNull()
{
Session?.Dispose();
Session = null;
}
}
}
``` |
b62db9a7-5051-494e-b471-d9600058ddfe | {
"language": "C#"
} | ```c#
namespace Gu.Analyzers.Test.GU0009UseNamedParametersForBooleansTests
{
using System.Threading.Tasks;
using NUnit.Framework;
internal class Diagnostics : DiagnosticVerifier<Analyzers.GU0009UseNamedParametersForBooleans>
{
[Test]
public async Task UnnamedBooleanParameters()
{
var testCode = @"
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Foo
{
public void Floof(int howMuch, bool useFluffyBuns)
{
}
public void Another()
{
Floof(42, ↓false);
}
}";
var expected = this.CSharpDiagnostic()
.WithLocationIndicated(ref testCode)
.WithMessage("The boolean parameter is not named.");
await this.VerifyCSharpDiagnosticAsync(new[] { testCode }, expected)
.ConfigureAwait(false);
}
}
}```
Test for different named for bool | ```c#
namespace Gu.Analyzers.Test.GU0009UseNamedParametersForBooleansTests
{
using System.Threading.Tasks;
using NUnit.Framework;
internal class Diagnostics : DiagnosticVerifier<Analyzers.GU0009UseNamedParametersForBooleans>
{
[Test]
public async Task UnnamedBooleanParameters()
{
var testCode = @"
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Foo
{
public void Floof(int howMuch, bool useFluffyBuns)
{
}
public void Another()
{
Floof(42, ↓false);
}
}";
var expected = this.CSharpDiagnostic()
.WithLocationIndicated(ref testCode)
.WithMessage("The boolean parameter is not named.");
await this.VerifyCSharpDiagnosticAsync(new[] { testCode }, expected)
.ConfigureAwait(false);
}
[Test]
public async Task HandlesAnAlias()
{
var testCode = @"
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Alias = System.Boolean;
public class Foo
{
public void Floof(int howMuch, Alias useFluffyBuns)
{
}
public void Another()
{
Floof(42, ↓false);
}
}";
var expected = this.CSharpDiagnostic()
.WithLocationIndicated(ref testCode)
.WithMessage("The boolean parameter is not named.");
await this.VerifyCSharpDiagnosticAsync(new[] { testCode }, expected)
.ConfigureAwait(false);
}
[Test]
public async Task HandlesAFullyQualifiedName()
{
var testCode = @"
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Foo
{
public void Floof(int howMuch, System.Boolean useFluffyBuns)
{
}
public void Another()
{
Floof(42, ↓false);
}
}";
var expected = this.CSharpDiagnostic()
.WithLocationIndicated(ref testCode)
.WithMessage("The boolean parameter is not named.");
await this.VerifyCSharpDiagnosticAsync(new[] { testCode }, expected)
.ConfigureAwait(false);
}
}
}``` |
878ab86b-8279-4720-8be4-4babbdbc4649 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BasicallyMe.RobinhoodNet;
namespace RobinhoodDesktop.HomePage
{
public partial class HomePageForm : Form
{
public HomePageForm()
{
InitializeComponent();
//HomePage.AccountSummaryChart accountChart = new HomePage.AccountSummaryChart();
//accountChart.Size = new Size(this.Width - 20, this.Height - 20);
//this.Controls.Add(accountChart);
StockChart plot = new StockChart();
plot.SetChartData(GenerateExampleData());
this.Controls.Add(plot.Canvas);
}
private static System.Data.DataTable GenerateExampleData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Time", typeof(DateTime));
dt.Columns.Add("Price", typeof(float));
;
try
{
var rh = new RobinhoodClient();
var history = rh.DownloadHistory("AMD", "5minute", "week").Result;
foreach (var p in history.HistoricalInfo)
{
dt.Rows.Add(p.BeginsAt, (float)p.OpenPrice);
}
}
catch
{
Environment.Exit(1);
}
return dt;
}
}
}
```
Convert time received from Robinhood to local before charting it. | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BasicallyMe.RobinhoodNet;
namespace RobinhoodDesktop.HomePage
{
public partial class HomePageForm : Form
{
public HomePageForm()
{
InitializeComponent();
//HomePage.AccountSummaryChart accountChart = new HomePage.AccountSummaryChart();
//accountChart.Size = new Size(this.Width - 20, this.Height - 20);
//this.Controls.Add(accountChart);
StockChart plot = new StockChart();
plot.SetChartData(GenerateExampleData());
this.Controls.Add(plot.Canvas);
}
private static System.Data.DataTable GenerateExampleData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Time", typeof(DateTime));
dt.Columns.Add("Price", typeof(float));
try
{
var rh = new RobinhoodClient();
var history = rh.DownloadHistory("AMD", "5minute", "week").Result;
foreach (var p in history.HistoricalInfo)
{
dt.Rows.Add(p.BeginsAt.ToLocalTime(), (float)p.OpenPrice);
}
}
catch(Exception ex)
{
Environment.Exit(1);
}
return dt;
}
}
}
``` |
ad3c5dd6-592b-4fab-bc2b-9e61e5cfd983 | {
"language": "C#"
} | ```c#
using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;
using Raven.Client;
using Raven.Client.Embedded;
namespace CGO.Web.NinjectModules
{
public class RavenModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope();
Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
private static IDocumentStore InitialiseDocumentStore()
{
var documentStore = new EmbeddableDocumentStore
{
DataDirectory = "CGO.raven",
UseEmbeddedHttpServer = true
};
documentStore.InitializeProfiling();
documentStore.Initialize();
return documentStore;
}
}
}```
Fix RavenConfiguration for Embedded mode. | ```c#
using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;
using Raven.Client;
using Raven.Client.Embedded;
namespace CGO.Web.NinjectModules
{
public class RavenModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope();
Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
private static IDocumentStore InitialiseDocumentStore()
{
var documentStore = new EmbeddableDocumentStore
{
DataDirectory = "CGO.raven",
UseEmbeddedHttpServer = true,
Configuration = { Port = 28645 }
};
documentStore.InitializeProfiling();
documentStore.Initialize();
return documentStore;
}
}
}``` |
dbd17224-3ff6-4e9b-8c1c-1fc3e92e6580 | {
"language": "C#"
} | ```c#
using System;
using Tralus.Framework.BusinessModel.Entities;
namespace Tralus.Framework.Migration.Migrations
{
using System.Data.Entity.Migrations;
public sealed class Configuration : TralusDbMigrationConfiguration<Data.FrameworkDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Tralus.Framework.Data.FrameworkDbContext context)
{
base.Seed(context);
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
//var administratorRole = new Role(true)
//{
// Name = "Administrators",
// IsAdministrative = true,
// CanEditModel = true,
//};
context.Set<Role>().AddOrUpdate(new Role(true)
{
Id = new Guid("F011D97A-CDA4-46F4-BE33-B48C4CAB9A3E"),
Name = "Administrators",
IsAdministrative = true,
CanEditModel = true,
});
}
}
}
```
Correct Administrators Role (set IsAdministrator to false) | ```c#
using System;
using Tralus.Framework.BusinessModel.Entities;
namespace Tralus.Framework.Migration.Migrations
{
using System.Data.Entity.Migrations;
public sealed class Configuration : TralusDbMigrationConfiguration<Data.FrameworkDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Tralus.Framework.Data.FrameworkDbContext context)
{
base.Seed(context);
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
//var administratorRole = new Role(true)
//{
// Name = "Administrators",
// IsAdministrative = true,
// CanEditModel = true,
//};
context.Set<Role>().AddOrUpdate(new Role(true)
{
Id = new Guid("F011D97A-CDA4-46F4-BE33-B48C4CAB9A3E"),
Name = "Administrators",
IsAdministrative = false,
CanEditModel = true,
});
}
}
}
``` |
fd93ba5c-52ca-40d4-be53-f501babdc433 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal static class SuggestionsOptions
{
private const string FeatureName = "SuggestionsOptions";
public static readonly Option2<bool> Asynchronous = new(FeatureName, nameof(Asynchronous), defaultValue: true,
new RoamingProfileStorageLocation("TextEditor.Specific.Suggestions.Asynchronous2"));
public static readonly Option2<bool> AsynchronousQuickActionsDisableFeatureFlag = new(FeatureName, nameof(AsynchronousQuickActionsDisableFeatureFlag), defaultValue: false,
new FeatureFlagStorageLocation("Roslyn.AsynchronousQuickActionsDisable"));
}
}
```
Add new option so anyone who set the option value in 17.0 doesn't forever disable async lightbulbs in 17.1 and onwards | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal static class SuggestionsOptions
{
private const string FeatureName = "SuggestionsOptions";
public static readonly Option2<bool> Asynchronous = new(FeatureName, nameof(Asynchronous), defaultValue: true,
new RoamingProfileStorageLocation("TextEditor.Specific.Suggestions.Asynchronous3"));
public static readonly Option2<bool> AsynchronousQuickActionsDisableFeatureFlag = new(FeatureName, nameof(AsynchronousQuickActionsDisableFeatureFlag), defaultValue: false,
new FeatureFlagStorageLocation("Roslyn.AsynchronousQuickActionsDisable"));
}
}
``` |
0fc29fee-f4db-4897-903b-2b5d888957fb | {
"language": "C#"
} | ```c#
// Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
[Collection(nameof(SpannerFixture))]
public class QueryDataWithArrayOfStructAsyncTest
{
private readonly SpannerFixture _spannerFixture;
public QueryDataWithArrayOfStructAsyncTest(SpannerFixture spannerFixture)
{
_spannerFixture = spannerFixture;
}
[Fact]
public async Task TestQueryDataWithArrayOfStructAsync()
{
QueryDataWithArrayOfStructAsyncSample sample = new QueryDataWithArrayOfStructAsyncSample();
var singerIds = await sample.QueryDataWithArrayOfStructAsync(_spannerFixture.ProjectId, _spannerFixture.InstanceId, _spannerFixture.DatabaseId);
var expectedSingerIds = new List<int> { 8, 7, 6 };
Assert.Equal(singerIds.Intersect(expectedSingerIds), expectedSingerIds);
}
}
```
Test was expecting ordered data without order by. | ```c#
// Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Threading.Tasks;
using Xunit;
[Collection(nameof(SpannerFixture))]
public class QueryDataWithArrayOfStructAsyncTest
{
private readonly SpannerFixture _spannerFixture;
public QueryDataWithArrayOfStructAsyncTest(SpannerFixture spannerFixture)
{
_spannerFixture = spannerFixture;
}
[Fact]
public async Task TestQueryDataWithArrayOfStructAsync()
{
QueryDataWithArrayOfStructAsyncSample sample = new QueryDataWithArrayOfStructAsyncSample();
var singerIds = await sample.QueryDataWithArrayOfStructAsync(_spannerFixture.ProjectId, _spannerFixture.InstanceId, _spannerFixture.DatabaseId);
Assert.Contains(6, singerIds);
Assert.Contains(7, singerIds);
Assert.Contains(8, singerIds);
}
}
``` |
22149f72-9f2d-4496-b121-e3d72a1f046a | {
"language": "C#"
} | ```c#
using SPAD.neXt.Interfaces.Profile;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace SPAD.neXt.Interfaces.Configuration
{
public interface ISettingsProvider : IProfileOptionsProvider, IWindowPlacementProvider
{ }
public interface IProfileOptionsProvider
{
IProfileOption AddOption(string key, Interfaces.Profile.ProfileOptionTypes type, string defaultValue, bool needrestart = false, bool editable = false, bool hidden = false,string groupName="Other");
IProfileOption GetOption(string key);
void SetOption(string key, string value);
}
public interface IWindowPlacementProvider
{
IWindowPlacement GetWindowPlacement(string key);
void SetWindowPlacement(IWindowPlacement placement);
}
public interface IWindowPlacement
{
string Key { get; }
double Top { get; set; }
double Left { get; set; }
double Height { get; set; }
double Width { get; set; }
bool HasValues { get; }
void ApplyPlacement(Window w);
bool SavePlacement(Window w);
T GetOption<T>(string key, T defaultValue = default(T));
void SetOption(string key, object value);
}
}
```
Add option to enforce placement even if turned off | ```c#
using SPAD.neXt.Interfaces.Profile;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace SPAD.neXt.Interfaces.Configuration
{
public interface ISettingsProvider : IProfileOptionsProvider, IWindowPlacementProvider
{ }
public interface IProfileOptionsProvider
{
IProfileOption AddOption(string key, Interfaces.Profile.ProfileOptionTypes type, string defaultValue, bool needrestart = false, bool editable = false, bool hidden = false,string groupName="Other");
IProfileOption GetOption(string key);
void SetOption(string key, string value);
}
public interface IWindowPlacementProvider
{
IWindowPlacement GetWindowPlacement(string key);
void SetWindowPlacement(IWindowPlacement placement);
}
public interface IWindowPlacement
{
string Key { get; }
double Top { get; set; }
double Left { get; set; }
double Height { get; set; }
double Width { get; set; }
bool HasValues { get; }
void ApplyPlacement(Window w, bool force = false);
bool SavePlacement(Window w);
T GetOption<T>(string key, T defaultValue = default(T));
void SetOption(string key, object value);
}
}
``` |
e6de9969-1cad-4e46-afbb-1705cbb02f3a | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Tests.Components
{
public class TestSceneTournamentBeatmapPanel : TournamentTestScene
{
[BackgroundDependencyLoader]
private void load()
{
var req = new GetBeatmapRequest(new APIBeatmap { OnlineID = 1091460 });
req.Success += success;
API.Queue(req);
}
private void success(APIBeatmap beatmap)
{
Add(new TournamentBeatmapPanel(beatmap)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
}
}
```
Revert tournament beatmap panel test change with comment | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Tests.Components
{
public class TestSceneTournamentBeatmapPanel : TournamentTestScene
{
/// <remarks>
/// Warning: the below API instance is actually the online API, rather than the dummy API provided by the test.
/// It cannot be trivially replaced because setting <see cref="OsuTestScene.UseOnlineAPI"/> to <see langword="true"/> causes <see cref="OsuTestScene.API"/> to no longer be usable.
/// </remarks>
[Resolved]
private IAPIProvider api { get; set; }
[BackgroundDependencyLoader]
private void load()
{
var req = new GetBeatmapRequest(new APIBeatmap { OnlineID = 1091460 });
req.Success += success;
api.Queue(req);
}
private void success(APIBeatmap beatmap)
{
Add(new TournamentBeatmapPanel(beatmap)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
}
}
``` |
927f52b7-444d-4243-b068-af68e966f285 | {
"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 JetBrains.Annotations;
using osu.Game.Audio;
namespace osu.Game.Skinning
{
/// <summary>
/// Provides pooled samples to be used by <see cref="SkinnableSound"/>s.
/// </summary>
internal interface IPooledSampleProvider
{
/// <summary>
/// Retrieves a <see cref="PoolableSkinnableSample"/> from a pool.
/// </summary>
/// <param name="sampleInfo">The <see cref="SampleInfo"/> describing the sample to retrieve..</param>
/// <returns>The <see cref="PoolableSkinnableSample"/>.</returns>
[CanBeNull]
PoolableSkinnableSample GetPooledSample(ISampleInfo sampleInfo);
}
}
```
Trim double full-stop in xmldoc | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using JetBrains.Annotations;
using osu.Game.Audio;
namespace osu.Game.Skinning
{
/// <summary>
/// Provides pooled samples to be used by <see cref="SkinnableSound"/>s.
/// </summary>
internal interface IPooledSampleProvider
{
/// <summary>
/// Retrieves a <see cref="PoolableSkinnableSample"/> from a pool.
/// </summary>
/// <param name="sampleInfo">The <see cref="SampleInfo"/> describing the sample to retrieve.</param>
/// <returns>The <see cref="PoolableSkinnableSample"/>.</returns>
[CanBeNull]
PoolableSkinnableSample GetPooledSample(ISampleInfo sampleInfo);
}
}
``` |
5b1157ad-953e-4e7c-928e-91246eed022a | {
"language": "C#"
} | ```c#
#if DEBUG
using System;
using System.IO;
using System.Reflection;
using SilentHunter.FileFormats.IO;
namespace SilentHunter.FileFormats.Extensions
{
internal static class DebugExtensions
{
internal static string GetBaseStreamName(this Stream s)
{
Stream baseStream = s;
if (baseStream is RegionStream)
{
baseStream = ((RegionStream)s).BaseStream;
}
// TODO: can we remove reflection to get base stream?? Even though we only use this in DEBUG..
if (baseStream is BufferedStream)
{
// Get the private field _s.
baseStream = (Stream)typeof(BufferedStream).GetField("_stream", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(baseStream);
}
Type t = baseStream.GetType();
if (t.Name == "SyncStream")
{
baseStream = (Stream)t.GetField("_stream", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(baseStream);
}
if (baseStream is BufferedStream)
{
// Get the private field _s.
baseStream = (Stream)typeof(BufferedStream).GetField("_stream", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(baseStream);
}
if (baseStream is FileStream fileStream)
{
return fileStream.Name;
}
return null;
}
}
}
#endif```
Exclude debug extensions from coverage | ```c#
#if DEBUG
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using SilentHunter.FileFormats.IO;
namespace SilentHunter.FileFormats.Extensions
{
[ExcludeFromCodeCoverage]
internal static class DebugExtensions
{
internal static string GetBaseStreamName(this Stream s)
{
Stream baseStream = s;
if (baseStream is RegionStream)
{
baseStream = ((RegionStream)s).BaseStream;
}
// TODO: can we remove reflection to get base stream?? Even though we only use this in DEBUG..
if (baseStream is BufferedStream)
{
// Get the private field _s.
baseStream = (Stream)typeof(BufferedStream).GetField("_stream", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(baseStream);
}
Type t = baseStream.GetType();
if (t.Name == "SyncStream")
{
baseStream = (Stream)t.GetField("_stream", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(baseStream);
}
if (baseStream is BufferedStream)
{
// Get the private field _s.
baseStream = (Stream)typeof(BufferedStream).GetField("_stream", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(baseStream);
}
if (baseStream is FileStream fileStream)
{
return fileStream.Name;
}
return null;
}
}
}
#endif``` |
25662d35-bdf1-4aa7-82ba-099ffc18f0fb | {
"language": "C#"
} | ```c#
using Microsoft.Owin;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace CompleteSample.Authentication
{
public class AuthenticationMiddleware : OwinMiddleware
{
public AuthenticationMiddleware(OwinMiddleware next)
: base(next)
{
}
public override Task Invoke(IOwinContext context)
{
string[] values;
BasicAuthenticationCredentials credentials;
if (context.Request.Headers.TryGetValue("Authorization", out values)
&& BasicAuthenticationCredentials.TryParse(values.First(), out credentials))
{
if (Authenticate(credentials.UserName, credentials.Password))
{
var identity = new GenericIdentity(credentials.UserName);
context.Request.User = new GenericPrincipal(identity, new string[0]);
}
else
{
context.Response.StatusCode = 401; // Unauthorized
}
}
return Next.Invoke(context);
}
private static bool Authenticate(string userName, string password)
{
// TODO: use a better authentication mechanism ;-)
return userName == "fvilers" && password == "test";
}
}
}
```
Update how the 401 status code is returned when authenticating | ```c#
using Microsoft.Owin;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace CompleteSample.Authentication
{
public class AuthenticationMiddleware : OwinMiddleware
{
public AuthenticationMiddleware(OwinMiddleware next)
: base(next)
{
}
public override Task Invoke(IOwinContext context)
{
string[] values;
BasicAuthenticationCredentials credentials;
if (context.Request.Headers.TryGetValue("Authorization", out values)
&& BasicAuthenticationCredentials.TryParse(values.First(), out credentials)
&& Authenticate(credentials.UserName, credentials.Password))
{
var identity = new GenericIdentity(credentials.UserName);
context.Request.User = new GenericPrincipal(identity, new string[0]);
}
else
{
context.Response.StatusCode = 401; // Unauthorized
}
return Next.Invoke(context);
}
private static bool Authenticate(string userName, string password)
{
// TODO: use a better authentication mechanism ;-)
return userName == "fvilers" && password == "test";
}
}
}
``` |
59ee2200-0e41-472e-b86e-53df73ec10de | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Windows;
using System.Windows.Data;
using NuGet;
namespace PackageExplorer {
public class FrameworkAssemblyReferenceConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
var frameworkNames = (IEnumerable<FrameworkName>)value;
return frameworkNames == null ? String.Empty : String.Join("; ", frameworkNames);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
string stringValue = (string)value;
if (!String.IsNullOrEmpty(stringValue)) {
string[] parts = stringValue.Split(new char[] {';', ','}, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 0) {
FrameworkName[] names = new FrameworkName[parts.Length];
for (int i = 0; i < parts.Length; i++) {
try {
names[i] = VersionUtility.ParseFrameworkName(parts[i]);
if (names[i] == VersionUtility.UnsupportedFrameworkName) {
return DependencyProperty.UnsetValue;
}
}
catch (ArgumentException) {
return DependencyProperty.UnsetValue;
}
}
return names;
}
}
return DependencyProperty.UnsetValue;
}
}
}
```
Fix an issue with the binding converter of framework assembly reference. | ```c#
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Windows;
using System.Windows.Data;
using NuGet;
namespace PackageExplorer {
public class FrameworkAssemblyReferenceConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
var frameworkNames = (IEnumerable<FrameworkName>)value;
return frameworkNames == null ? String.Empty : String.Join("; ", frameworkNames);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
string stringValue = (string)value;
if (!String.IsNullOrEmpty(stringValue)) {
string[] parts = stringValue.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 0) {
FrameworkName[] names = new FrameworkName[parts.Length];
for (int i = 0; i < parts.Length; i++) {
try {
names[i] = VersionUtility.ParseFrameworkName(parts[i]);
if (names[i] == VersionUtility.UnsupportedFrameworkName) {
return DependencyProperty.UnsetValue;
}
}
catch (ArgumentException) {
return DependencyProperty.UnsetValue;
}
}
return names;
}
}
return new FrameworkName[0];
}
}
}
``` |
e4b7ea02-ef66-4d6d-a357-4827d2c975f2 | {
"language": "C#"
} | ```c#
using Serilog.Core;
using Serilog.Events;
namespace Umbraco.Core.Logging.SerilogExtensions
{
/// <summary>
/// This is used to create a new property in Logs called 'Log4NetLevel'
/// So that we can map Serilog levels to Log4Net levels - so log files stay consistent
/// </summary>
public class Log4NetLevelMapperEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var log4NetLevel = string.Empty;
switch (logEvent.Level)
{
case LogEventLevel.Debug:
log4NetLevel = "DEBUG";
break;
case LogEventLevel.Error:
log4NetLevel = "ERROR";
break;
case LogEventLevel.Fatal:
log4NetLevel = "FATAL";
break;
case LogEventLevel.Information:
log4NetLevel = "INFO ";
break;
case LogEventLevel.Verbose:
log4NetLevel = "ALL ";
break;
case LogEventLevel.Warning:
log4NetLevel = "WARN ";
break;
}
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Log4NetLevel", log4NetLevel));
}
}
}
```
Use string.PadRight to be more explicit with what we are doing with the Log4Net level property enricher | ```c#
using Serilog.Core;
using Serilog.Events;
namespace Umbraco.Core.Logging.SerilogExtensions
{
/// <summary>
/// This is used to create a new property in Logs called 'Log4NetLevel'
/// So that we can map Serilog levels to Log4Net levels - so log files stay consistent
/// </summary>
public class Log4NetLevelMapperEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var log4NetLevel = string.Empty;
switch (logEvent.Level)
{
case LogEventLevel.Debug:
log4NetLevel = "DEBUG";
break;
case LogEventLevel.Error:
log4NetLevel = "ERROR";
break;
case LogEventLevel.Fatal:
log4NetLevel = "FATAL";
break;
case LogEventLevel.Information:
log4NetLevel = "INFO";
break;
case LogEventLevel.Verbose:
log4NetLevel = "ALL";
break;
case LogEventLevel.Warning:
log4NetLevel = "WARN";
break;
}
//Pad string so that all log levels are 5 chars long (needed to keep the txt log file lined up nicely)
log4NetLevel = log4NetLevel.PadRight(5);
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Log4NetLevel", log4NetLevel));
}
}
}
``` |
92970dc9-6461-4f40-b1dc-a1817402cc78 | {
"language": "C#"
} | ```c#
using System;
using AGS.API;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AGS.Engine
{
public class AGSDialogLayout : IDialogLayout
{
private IGame _game;
public AGSDialogLayout(IGame game)
{
_game = game;
}
#region IDialogLayout implementation
public async Task LayoutAsync(IObject dialogGraphics, IList<IDialogOption> options)
{
float y = 0f;
for (int index = options.Count - 1; index >= 0; index--)
{
IDialogOption option = options[index];
_game.State.UI.Add(option.Label);
if (!option.Label.Visible) continue;
option.Label.Y = y;
int retries = 100;
while (option.Label.TextHeight <= 5f && retries > 0)
{
await Task.Delay(1); //todo: find a better way (we need to wait at least one render loop for the text height to be correct)
retries--;
}
y += option.Label.TextHeight;
}
if (dialogGraphics.Image == null)
{
dialogGraphics.Image = new EmptyImage (_game.Settings.VirtualResolution.Width, y);
}
dialogGraphics.Animation.Sprite.ScaleTo(_game.Settings.VirtualResolution.Width, y);
}
#endregion
}
}
```
Increase the amount of retries when rendering the dialog | ```c#
using System;
using AGS.API;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AGS.Engine
{
public class AGSDialogLayout : IDialogLayout
{
private IGame _game;
public AGSDialogLayout(IGame game)
{
_game = game;
}
#region IDialogLayout implementation
public async Task LayoutAsync(IObject dialogGraphics, IList<IDialogOption> options)
{
float y = 0f;
for (int index = options.Count - 1; index >= 0; index--)
{
IDialogOption option = options[index];
_game.State.UI.Add(option.Label);
if (!option.Label.Visible) continue;
option.Label.Y = y;
int retries = 1000;
while (option.Label.TextHeight <= 5f && retries > 0)
{
await Task.Delay(1); //todo: find a better way (we need to wait at least one render loop for the text height to be correct)
retries--;
}
y += option.Label.TextHeight;
}
if (dialogGraphics.Image == null)
{
dialogGraphics.Image = new EmptyImage (_game.Settings.VirtualResolution.Width, y);
}
dialogGraphics.Animation.Sprite.ScaleTo(_game.Settings.VirtualResolution.Width, y);
}
#endregion
}
}
``` |
05c60b17-b8f4-44ea-8aa6-f150d94e928b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Apollo.Converters;
using Branch.Packages.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Apollo.Middleware
{
public static class ExceptionMiddleware
{
private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new ExceptionConverter() },
ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() },
};
public static async Task Handle(HttpContext ctx, Func<Task> next)
{
try
{
await next.Invoke();
}
catch (Exception ex)
{
// TODO(0xdeafcafe): Handle this
if (!(ex is BranchException))
{
Console.WriteLine(ex);
throw;
}
var json = JsonConvert.SerializeObject(ex, jsonSerializerSettings);
ctx.Response.StatusCode = (int) HttpStatusCode.InternalServerError;;
ctx.Response.ContentType = "application/json";
await ctx.Response.WriteAsync(json);
}
}
}
}
```
Return some error if we fuck up hard | ```c#
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Apollo.Converters;
using Branch.Packages.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Apollo.Middleware
{
public static class ExceptionMiddleware
{
private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new ExceptionConverter() },
ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() },
};
public static async Task Handle(HttpContext ctx, Func<Task> next)
{
try
{
await next.Invoke();
}
catch (Exception ex)
{
var branchEx = ex as BranchException;
// TODO(0xdeafcafe): Handle this
if (!(ex is BranchException))
{
Console.WriteLine(ex);
branchEx = new BranchException("unknown_error");
}
var json = JsonConvert.SerializeObject(branchEx, jsonSerializerSettings);
ctx.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
ctx.Response.ContentType = "application/json";
await ctx.Response.WriteAsync(json);
}
}
}
}
``` |
a9850490-7afa-4f9d-a45a-4e014ebf1e43 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CatchAllRule.Controllers
{
public class EverythingController : Controller
{
// GET: Everything
public ActionResult Index()
{
return View();
}
}
}```
Add log statement to track outdated links | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CatchAllRule.Controllers
{
public class EverythingController : Controller
{
// GET: Everything
public ActionResult Index()
{
// use your logger to track outdated links:
System.Diagnostics.Debug.WriteLine(
$"Update link on page '{Request.UrlReferrer}' for '{Request.Url}'"
);
return View();
}
}
}``` |
afb1c9e2-2d39-4cfc-bf13-d8949382adc7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FluentAutomation.Tests.Pages
{
public class InputsPage : PageObject<InputsPage>
{
public InputsPage(FluentTest test)
: base(test)
{
this.Url = "/Inputs";
}
public string TextControlSelector = "#text-control";
public string TextareaControlSelector = "#textarea-control";
public string SelectControlSelector = "#select-control";
public string MultiSelectControlSelector = "#multi-select-control";
public string ButtonControlSelector = "#button-control";
public string InputButtonControlSelector = "#input-button-control";
public string TextChangedTextSelector = "#text-changed";
public string ButtonClickedTextSelector = "#button-clicked";
}
}
```
Fix for text-changed selector in tests | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FluentAutomation.Tests.Pages
{
public class InputsPage : PageObject<InputsPage>
{
public InputsPage(FluentTest test)
: base(test)
{
this.Url = "/Inputs";
}
public string TextControlSelector = "#text-control";
public string TextareaControlSelector = "#textarea-control";
public string SelectControlSelector = "#select-control";
public string MultiSelectControlSelector = "#multi-select-control";
public string ButtonControlSelector = "#button-control";
public string InputButtonControlSelector = "#input-button-control";
public string TextChangedTextSelector = "#text-control-changed";
public string ButtonClickedTextSelector = "#button-clicked";
}
}
``` |
16927893-4943-4c3f-98f3-fe17716a7e57 | {
"language": "C#"
} | ```c#
using System;
using RestSharp;
using RestSharp.Contrib;
namespace AppHarbor.Commands
{
[CommandHelp("Login to AppHarbor")]
public class LoginAuthCommand : ICommand
{
private readonly IAccessTokenConfiguration _accessTokenConfiguration;
public LoginAuthCommand(IAccessTokenConfiguration accessTokenConfiguration)
{
_accessTokenConfiguration = accessTokenConfiguration;
}
public void Execute(string[] arguments)
{
if (_accessTokenConfiguration.GetAccessToken() != null)
{
throw new CommandException("You're already logged in");
}
Console.WriteLine("Username:");
var username = Console.ReadLine();
Console.WriteLine("Password:");
var password = Console.ReadLine();
var accessToken = GetAccessToken(username, password);
_accessTokenConfiguration.SetAccessToken(accessToken);
}
public virtual string GetAccessToken(string username, string password)
{
//NOTE: Remove when merged into AppHarbor.NET library
var restClient = new RestClient("https://appharbor-token-client.apphb.com");
var request = new RestRequest("/token", Method.POST);
request.AddParameter("username", username);
request.AddParameter("password", password);
var response = restClient.Execute(request);
return HttpUtility.ParseQueryString(response.Content.Split('=', '&')[1])["access_token"];
}
}
}
```
Throw exception if access token is null | ```c#
using System;
using RestSharp;
using RestSharp.Contrib;
namespace AppHarbor.Commands
{
[CommandHelp("Login to AppHarbor")]
public class LoginAuthCommand : ICommand
{
private readonly IAccessTokenConfiguration _accessTokenConfiguration;
public LoginAuthCommand(IAccessTokenConfiguration accessTokenConfiguration)
{
_accessTokenConfiguration = accessTokenConfiguration;
}
public void Execute(string[] arguments)
{
if (_accessTokenConfiguration.GetAccessToken() != null)
{
throw new CommandException("You're already logged in");
}
Console.WriteLine("Username:");
var username = Console.ReadLine();
Console.WriteLine("Password:");
var password = Console.ReadLine();
var accessToken = GetAccessToken(username, password);
_accessTokenConfiguration.SetAccessToken(accessToken);
}
public virtual string GetAccessToken(string username, string password)
{
//NOTE: Remove when merged into AppHarbor.NET library
var restClient = new RestClient("https://appharbor-token-client.apphb.com");
var request = new RestRequest("/token", Method.POST);
request.AddParameter("username", username);
request.AddParameter("password", password);
var response = restClient.Execute(request);
var accessToken = HttpUtility.ParseQueryString(response.Content.Split('=', '&')[1])["access_token"];
if (accessToken == null)
{
throw new CommandException("Couldn't log in. Try again");
}
return accessToken;
}
}
}
``` |
f0b2ca0a-a23e-4fa6-b7bc-fcd5a6324ac1 | {
"language": "C#"
} | ```c#
using Glimpse.Web;
using System;
using System.Text;
using System.Threading.Tasks;
namespace Glimpse.Server.Web.Resources
{
public class HelloGlimpseResource : IRequestHandler
{
public bool WillHandle(IContext context)
{
return context.Request.Path.StartsWith("/Glimpse");
}
public async Task Handle(IContext context)
{
var response = context.Response;
response.SetHeader("Content-Type", "text/plain");
var data = Encoding.UTF8.GetBytes("Hello world, Glimpse!");
await response.WriteAsync(data);
}
}
}```
Make test resource more specific | ```c#
using Glimpse.Web;
using System;
using System.Text;
using System.Threading.Tasks;
namespace Glimpse.Server.Web.Resources
{
public class HelloGlimpseResource : IRequestHandler
{
public bool WillHandle(IContext context)
{
return context.Request.Path == "/Glimpse";
}
public async Task Handle(IContext context)
{
var response = context.Response;
response.SetHeader("Content-Type", "text/plain");
var data = Encoding.UTF8.GetBytes("Hello world, Glimpse!");
await response.WriteAsync(data);
}
}
}``` |
ef3dd93e-39a4-4753-8d9a-b53b9c41455f | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("lozanotek")]
[assembly: AssemblyProduct("MvcTurbine")]
[assembly: AssemblyCopyright("Copyright © lozanotek, inc. 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("3.2.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]```
Update the version to 3.2.1. | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("lozanotek")]
[assembly: AssemblyProduct("MvcTurbine")]
[assembly: AssemblyCopyright("Copyright © lozanotek, inc. 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("3.2.1.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]``` |
7f4985ca-057a-4684-bf0a-3aa68bb52227 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
namespace NMaier.SimpleDlna.Utilities
{
using Attribute = KeyValuePair<string, string>;
using System;
public sealed class AttributeCollection : IEnumerable<Attribute>
{
private readonly IList<Attribute> list = new List<Attribute>();
public int Count
{
get
{
return list.Count;
}
}
public ICollection<string> Keys
{
get
{
return (from i in list
select i.Key).ToList();
}
}
public ICollection<string> Values
{
get
{
return (from i in list
select i.Value).ToList();
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
public void Add(Attribute item)
{
list.Add(item);
}
public void Add(string key, string value)
{
list.Add(new Attribute(key, value));
}
public void Clear()
{
list.Clear();
}
public bool Contains(Attribute item)
{
return list.Contains(item);
}
public IEnumerator<Attribute> GetEnumerator()
{
return list.GetEnumerator();
}
public IEnumerable<string> GetValuesForKey(string key)
{
return from i in list
where StringComparer.CurrentCultureIgnoreCase.Equals(i.Key, key)
select i.Value;
}
}
}
```
Move using where it belongs | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace NMaier.SimpleDlna.Utilities
{
using Attribute = KeyValuePair<string, string>;
public sealed class AttributeCollection : IEnumerable<Attribute>
{
private readonly IList<Attribute> list = new List<Attribute>();
public int Count
{
get
{
return list.Count;
}
}
public ICollection<string> Keys
{
get
{
return (from i in list
select i.Key).ToList();
}
}
public ICollection<string> Values
{
get
{
return (from i in list
select i.Value).ToList();
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
public void Add(Attribute item)
{
list.Add(item);
}
public void Add(string key, string value)
{
list.Add(new Attribute(key, value));
}
public void Clear()
{
list.Clear();
}
public bool Contains(Attribute item)
{
return list.Contains(item);
}
public IEnumerator<Attribute> GetEnumerator()
{
return list.GetEnumerator();
}
public IEnumerable<string> GetValuesForKey(string key)
{
return from i in list
where StringComparer.CurrentCultureIgnoreCase.Equals(i.Key, key)
select i.Value;
}
}
}
``` |
166b797e-646d-4889-b89c-6085f2bfb241 | {
"language": "C#"
} | ```c#
namespace TraktOAuthAuthenticationExample
{
class Program
{
static void Main(string[] args)
{
}
}
}
```
Add implementation for oauth authentication example. | ```c#
namespace TraktOAuthAuthenticationExample
{
using System;
using System.Threading.Tasks;
using TraktApiSharp;
using TraktApiSharp.Authentication;
using TraktApiSharp.Exceptions;
class Program
{
private const string CLIENT_ID = "ENTER_CLIENT_ID_HERE";
private const string CLIENT_SECRET = "ENTER_CLIENT_SECRET_HERE";
private static TraktClient _client = null;
static void Main(string[] args)
{
try
{
SetupClient();
TryToOAuthAuthenticate().Wait();
var authorization = _client.Authorization;
if (authorization == null || !authorization.IsValid)
throw new InvalidOperationException("Trakt Client not authenticated for requests, that require OAuth");
}
catch (TraktException ex)
{
Console.WriteLine("-------------- Trakt Exception --------------");
Console.WriteLine($"Exception message: {ex.Message}");
Console.WriteLine($"Status code: {ex.StatusCode}");
Console.WriteLine($"Request URL: {ex.RequestUrl}");
Console.WriteLine($"Request message: {ex.RequestBody}");
Console.WriteLine($"Request response: {ex.Response}");
Console.WriteLine($"Server Reason Phrase: {ex.ServerReasonPhrase}");
Console.WriteLine("---------------------------------------------");
}
catch (Exception ex)
{
Console.WriteLine("-------------- Exception --------------");
Console.WriteLine($"Exception message: {ex.Message}");
Console.WriteLine("---------------------------------------");
}
Console.ReadLine();
}
static void SetupClient()
{
if (_client == null)
{
_client = new TraktClient(CLIENT_ID, CLIENT_SECRET);
if (!_client.IsValidForAuthenticationProcess)
throw new InvalidOperationException("Trakt Client not valid for authentication");
}
}
static async Task TryToOAuthAuthenticate()
{
var authorizationUrl = _client.OAuth.CreateAuthorizationUrl();
if (!string.IsNullOrEmpty(authorizationUrl))
{
Console.WriteLine("You have to authenticate this application.");
Console.WriteLine("Please visit the following webpage:");
Console.WriteLine($"{authorizationUrl}\n");
Console.Write("Enter the PIN code from Trakt.tv: ");
var code = Console.ReadLine();
if (!string.IsNullOrEmpty(code))
{
TraktAuthorization authorization = await _client.OAuth.GetAuthorizationAsync(code);
if (authorization != null && authorization.IsValid)
{
Console.WriteLine("-------------- Authentication successful --------------");
Console.WriteLine($"Created (UTC): {authorization.Created}");
Console.WriteLine($"Access Scope: {authorization.AccessScope.DisplayName}");
Console.WriteLine($"Refresh Possible: {authorization.IsRefreshPossible}");
Console.WriteLine($"Valid: {authorization.IsValid}");
Console.WriteLine($"Token Type: {authorization.TokenType.DisplayName}");
Console.WriteLine($"Access Token: {authorization.AccessToken}");
Console.WriteLine($"Refresh Token: {authorization.RefreshToken}");
Console.WriteLine($"Token Expired: {authorization.IsExpired}");
Console.WriteLine($"Expires in {authorization.ExpiresIn / 3600 / 24} days");
Console.WriteLine("-------------------------------------------------------");
}
}
}
}
}
}
``` |
68fe95c6-6173-4abe-ac8e-93abce8ba6d5 | {
"language": "C#"
} | ```c#
namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
else if (discoveryContext == null)
{
throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null.");
}
else if (logger == null)
{
throw new ArgumentNullException("logger", "The message logger you have passed in is null. The message logger must not be null.");
}
else if (discoverySink == null)
{
throw new ArgumentNullException(
"discoverySink",
"The test case discovery sink you have passed in is null. The test case discovery sink must not be null.");
}
throw new NotImplementedException();
}
}
}```
Remove the test for the situation whree all the parameters are valid. | ```c#
namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
else if (discoveryContext == null)
{
throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null.");
}
else if (logger == null)
{
throw new ArgumentNullException("logger", "The message logger you have passed in is null. The message logger must not be null.");
}
else if (discoverySink == null)
{
throw new ArgumentNullException("discoverySink", "The test case discovery sink you have passed in is null. The test case discovery sink must not be null.");
}
throw new NotImplementedException();
}
}
}``` |
5f6cf4d3-48c4-45a6-89f4-9f29600c17ba | {
"language": "C#"
} | ```c#
using System;
using ColossalFramework;
using ICities;
namespace ModTools
{
public class LoadingExtension : LoadingExtensionBase
{
public override void OnCreated(ILoading loading)
{
base.OnCreated(loading);
ModToolsBootstrap.inMainMenu = false;
ModToolsBootstrap.Bootstrap();
}
public override void OnLevelLoaded(LoadMode mode)
{
base.OnLevelLoaded(mode);
CustomPrefabs.Bootstrap();
var appMode = Singleton<ToolManager>.instance.m_properties.m_mode;
if (ModTools.Instance.config.extendGamePanels && appMode == ItemClass.Availability.Game)
{
ModTools.Instance.gameObject.AddComponent<GamePanelExtender>();
}
}
public override void OnReleased()
{
base.OnReleased();
CustomPrefabs.Revert();
ModToolsBootstrap.inMainMenu = true;
ModToolsBootstrap.initialized = false;
}
}
}```
Set initialized to false in OnCreated | ```c#
using System;
using ColossalFramework;
using ICities;
namespace ModTools
{
public class LoadingExtension : LoadingExtensionBase
{
public override void OnCreated(ILoading loading)
{
base.OnCreated(loading);
ModToolsBootstrap.inMainMenu = false;
ModToolsBootstrap.initialized = false;
ModToolsBootstrap.Bootstrap();
}
public override void OnLevelLoaded(LoadMode mode)
{
base.OnLevelLoaded(mode);
CustomPrefabs.Bootstrap();
var appMode = Singleton<ToolManager>.instance.m_properties.m_mode;
if (ModTools.Instance.config.extendGamePanels && appMode == ItemClass.Availability.Game)
{
ModTools.Instance.gameObject.AddComponent<GamePanelExtender>();
}
}
public override void OnReleased()
{
base.OnReleased();
CustomPrefabs.Revert();
ModToolsBootstrap.inMainMenu = true;
ModToolsBootstrap.initialized = false;
}
}
}``` |
3e88806b-6531-41b4-9789-0eb6d611acc7 | {
"language": "C#"
} | ```c#
namespace Qvision.Umbraco.PollIt.Controllers.ApiControllers
{
using System.Net;
using System.Net.Http;
using System.Web.Http;
using global::Umbraco.Web.Editors;
using Qvision.Umbraco.PollIt.Attributes;
using Qvision.Umbraco.PollIt.CacheRefresher;
using Qvision.Umbraco.PollIt.Models.Pocos;
using Qvision.Umbraco.PollIt.Models.Repositories;
[CamelCase]
public class AnswerApiController : UmbracoAuthorizedJsonController
{
[HttpPost]
public HttpResponseMessage Post(Answer answer)
{
var result = AnswerRepository.Current.Save(answer);
if (result != null)
{
PollItCacheRefresher.ClearCache(answer.QuestionId);
this.Request.CreateResponse(HttpStatusCode.OK, answer);
}
return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Can't save answer");
}
[HttpDelete]
public HttpResponseMessage Delete(int id, int questionId)
{
using (var transaction = this.ApplicationContext.DatabaseContext.Database.GetTransaction())
{
if (ResponseRepository.Current.DeleteByAnswerId(id) && AnswerRepository.Current.Delete(id))
{
transaction.Complete();
PollItCacheRefresher.ClearCache(questionId);
return this.Request.CreateResponse(HttpStatusCode.OK);
}
}
return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Can't delete answer");
}
}
}```
Add missing return when creating Answer | ```c#
namespace Qvision.Umbraco.PollIt.Controllers.ApiControllers
{
using System.Net;
using System.Net.Http;
using System.Web.Http;
using global::Umbraco.Web.Editors;
using Qvision.Umbraco.PollIt.Attributes;
using Qvision.Umbraco.PollIt.CacheRefresher;
using Qvision.Umbraco.PollIt.Models.Pocos;
using Qvision.Umbraco.PollIt.Models.Repositories;
[CamelCase]
public class AnswerApiController : UmbracoAuthorizedJsonController
{
[HttpPost]
public HttpResponseMessage Post(Answer answer)
{
var result = AnswerRepository.Current.Save(answer);
if (result != null)
{
PollItCacheRefresher.ClearCache(answer.QuestionId);
return this.Request.CreateResponse(HttpStatusCode.OK, answer);
}
return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Can't save answer");
}
[HttpDelete]
public HttpResponseMessage Delete(int id, int questionId)
{
using (var transaction = this.ApplicationContext.DatabaseContext.Database.GetTransaction())
{
if (ResponseRepository.Current.DeleteByAnswerId(id) && AnswerRepository.Current.Delete(id))
{
transaction.Complete();
PollItCacheRefresher.ClearCache(questionId);
return this.Request.CreateResponse(HttpStatusCode.OK);
}
}
return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Can't delete answer");
}
}
}``` |
39b7c05d-2397-4680-8eae-31160c015e2d | {
"language": "C#"
} | ```c#
using System.Runtime.Serialization;
namespace GogoKit.Models.Response
{
[DataContract]
public class Seating
{
[DataMember(Name = "section")]
public string Section { get; set; }
[DataMember(Name = "row")]
public string Row { get; set; }
[DataMember(Name = "seat_from")]
public string SeatFrom { get; set; }
[DataMember(Name = "seat_to")]
public string SeatTo { get; set; }
[DataMember(Name = "mapping_status")]
public MappingStatus MappingStatus { get; set; }
}
public class MappingStatus
{
[DataMember(Name = "status")]
public MappingStatusEnum Status { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
}
public enum MappingStatusEnum
{
Unknown = 0,
Mapped = 1,
Unmapped = 2,
Ignored = 3,
Rejected = 4
}
}
```
Update status enum to match current data base setup | ```c#
using System.Runtime.Serialization;
namespace GogoKit.Models.Response
{
[DataContract]
public class Seating
{
[DataMember(Name = "section")]
public string Section { get; set; }
[DataMember(Name = "row")]
public string Row { get; set; }
[DataMember(Name = "seat_from")]
public string SeatFrom { get; set; }
[DataMember(Name = "seat_to")]
public string SeatTo { get; set; }
[DataMember(Name = "mapping_status")]
public MappingStatus MappingStatus { get; set; }
}
public class MappingStatus
{
[DataMember(Name = "status")]
public ApiMappingState Status { get; set; }
}
public enum ApiMappingState
{
Unknown = 0,
Mapped = 1,
Unmapped = 2,
Ignored = 3,
Rejected = 4
}
}
``` |
375c5227-8b87-47cc-ad4f-0c593e391f92 | {
"language": "C#"
} | ```c#
using System.Web.Http;
using Swashbuckle.Application;
using System;
namespace WebHost
{
internal static class SwaggerConfig
{
public static void Register(HttpConfiguration httpConfigurations)
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
httpConfigurations
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "Enttoi API");
c.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\Core.XML");
c.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\WebHost.XML");
})
.EnableSwaggerUi();
}
}
}
```
Check of XML file existance | ```c#
using System.Web.Http;
using Swashbuckle.Application;
using System;
using System.IO;
namespace WebHost
{
internal static class SwaggerConfig
{
public static void Register(HttpConfiguration httpConfigurations)
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
var coreXml = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\Core.XML");
var hostXml = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\WebHost.XML");
httpConfigurations
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "Enttoi API");
if (coreXml.Exists) c.IncludeXmlComments(coreXml.FullName);
if (hostXml.Exists) c.IncludeXmlComments(hostXml.FullName);
})
.EnableSwaggerUi();
}
}
}
``` |
1f4c7f72-12e5-4557-b06e-d0dbff47f63d | {
"language": "C#"
} | ```c#
<title>Hearts and Bones Dog Rescue - Pet Adoption - @ViewBag.Title</title>
@* Recommended meta tags for bootstrap *@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Hearts & Bones Rescue is a 501(c)3 non-profit organization dedicated to saving the lives of at-risk dogs and finding them loving, forever homes.">
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700|Permanent+Marker" rel="stylesheet">
<link rel="stylesheet" href="/Styles/materialize/materialize.min.css">
<link rel="stylesheet" href="/Styles/site.min.css">```
Update page title to ampersand | ```c#
<title>Hearts & Bones Dog Rescue - Pet Adoption - @ViewBag.Title</title>
@* Recommended meta tags for bootstrap *@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Hearts & Bones Rescue is a 501(c)3 non-profit organization dedicated to saving the lives of at-risk dogs and finding them loving, forever homes.">
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700|Permanent+Marker" rel="stylesheet">
<link rel="stylesheet" href="/Styles/materialize/materialize.min.css">
<link rel="stylesheet" href="/Styles/site.min.css">``` |
dc7fac49-b190-458a-85f1-6f3158337e61 | {
"language": "C#"
} | ```c#
#if !ODIN_INSPECTOR
using UnityEditor;
namespace Zenject
{
[CanEditMultipleObjects]
[CustomEditor(typeof(SceneContext))]
public class SceneContextEditor : RunnableContextEditor
{
SerializedProperty _contractNameProperty;
SerializedProperty _parentNamesProperty;
SerializedProperty _parentContractNameProperty;
SerializedProperty _parentNewObjectsUnderRootProperty;
public override void OnEnable()
{
base.OnEnable();
_contractNameProperty = serializedObject.FindProperty("_contractNames");
_parentNamesProperty = serializedObject.FindProperty("_parentContractNames");
_parentContractNameProperty = serializedObject.FindProperty("_parentContractName");
_parentNewObjectsUnderRootProperty = serializedObject.FindProperty("_parentNewObjectsUnderRoot");
}
protected override void OnGui()
{
base.OnGui();
EditorGUILayout.PropertyField(_contractNameProperty, true);
EditorGUILayout.PropertyField(_parentNamesProperty, true);
EditorGUILayout.PropertyField(_parentContractNameProperty);
EditorGUILayout.PropertyField(_parentNewObjectsUnderRootProperty);
}
}
}
#endif
```
Fix for scene context editor crash | ```c#
#if !ODIN_INSPECTOR
using UnityEditor;
namespace Zenject
{
[CanEditMultipleObjects]
[CustomEditor(typeof(SceneContext))]
public class SceneContextEditor : RunnableContextEditor
{
SerializedProperty _contractNameProperty;
SerializedProperty _parentNamesProperty;
SerializedProperty _parentNewObjectsUnderRootProperty;
public override void OnEnable()
{
base.OnEnable();
_contractNameProperty = serializedObject.FindProperty("_contractNames");
_parentNamesProperty = serializedObject.FindProperty("_parentContractNames");
_parentNewObjectsUnderRootProperty = serializedObject.FindProperty("_parentNewObjectsUnderRoot");
}
protected override void OnGui()
{
base.OnGui();
EditorGUILayout.PropertyField(_contractNameProperty, true);
EditorGUILayout.PropertyField(_parentNamesProperty, true);
EditorGUILayout.PropertyField(_parentNewObjectsUnderRootProperty);
}
}
}
#endif
``` |
1f039227-2fb2-4fcb-85dc-09b206328905 | {
"language": "C#"
} | ```c#
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Cimpress.Extensions.Http
{
public static class HttpResponseMessageExtensions
{
public static async Task LogAndThrowIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
{
if (!message.IsSuccessStatusCode)
{
var formattedMsg = await LogMessage(message, logger);
throw new Exception(formattedMsg);
}
}
public static async Task LogIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
{
if (!message.IsSuccessStatusCode)
{
await LogMessage(message, logger);
}
}
public static async Task<string> LogMessage(HttpResponseMessage message, ILogger logger)
{
var msg = await message.Content.ReadAsStringAsync();
var formattedMsg = $"Error processing request. Status code was {message.StatusCode} when calling '{message.RequestMessage.RequestUri}', message was '{msg}'";
logger.LogError(formattedMsg);
return formattedMsg;
}
}
}
```
Add option to throw an exception without logging it. | ```c#
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Cimpress.Extensions.Http
{
public static class HttpResponseMessageExtensions
{
public static async Task LogAndThrowIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
{
if (!message.IsSuccessStatusCode)
{
var formattedMsg = await LogMessage(message, logger);
throw new Exception(formattedMsg);
}
}
public static async Task LogIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
{
if (!message.IsSuccessStatusCode)
{
await LogMessage(message, logger);
}
}
public static async Task ThrowIfNotSuccessStatusCode(this HttpResponseMessage message)
{
if (!message.IsSuccessStatusCode)
{
var formattedMsg = await FormatErrorMessage(message);
throw new Exception(formattedMsg);
}
}
public static async Task<string> LogMessage(HttpResponseMessage message, ILogger logger)
{
string formattedMsg = await message.FormatErrorMessage();
logger.LogError(formattedMsg);
return formattedMsg;
}
public static async Task<string> FormatErrorMessage(this HttpResponseMessage message)
{
var msg = await message.Content.ReadAsStringAsync();
var formattedMsg = $"Error processing request. Status code was {message.StatusCode} when calling '{message.RequestMessage.RequestUri}', message was '{msg}'";
return formattedMsg;
}
}
}
``` |
c53f206a-e7b9-458f-ae9a-d692b46fa378 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Data.Common
{
public static class DbDataReaderExtension
{
public static System.Collections.ObjectModel.ReadOnlyCollection<DbColumn> GetColumnSchema(this DbDataReader reader)
{
if (reader is IDbColumnSchemaGenerator)
{
return ((IDbColumnSchemaGenerator)reader).GetColumnSchema();
}
throw new NotImplementedException();
}
}
}
```
Add the query for capability | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Data.Common
{
public static class DbDataReaderExtension
{
public static System.Collections.ObjectModel.ReadOnlyCollection<DbColumn> GetColumnSchema(this DbDataReader reader)
{
if (reader.CanProvideSchema())
{
return ((IDbColumnSchemaGenerator)reader).GetColumnSchema();
}
throw new NotImplementedException();
}
public static bool CanProvideSchema(this DbDataReader reader)
{
return reader is IDbColumnSchemaGenerator;
}
}
}
``` |
778113c7-2775-45d1-8575-736298e7e103 | {
"language": "C#"
} | ```c#
using PluginContracts;
using System;
using System.Collections.Generic;
using Xunit;
namespace PluginLoader.Tests
{
public class Plugins_Tests
{
[Fact]
public void PluginsFound()
{
// Arrange
var path = @"..\..\..\..\LAN\bin\Debug\netstandard1.3";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.NotEmpty(plugins);
}
[Fact]
public void PluginsNotFound()
{
// Arrange
var path = @".";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.Empty(plugins);
}
}
}
```
Change test method names to follow "Feature to be tested" pattern | ```c#
using PluginContracts;
using System;
using System.Collections.Generic;
using Xunit;
namespace PluginLoader.Tests
{
public class Plugins_Tests
{
[Fact]
public void PluginsFoundFromLibsFolder()
{
// Arrange
var path = @"..\..\..\..\LAN\bin\Debug\netstandard1.3";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.NotEmpty(plugins);
}
[Fact]
public void PluginsNotFoundFromCurrentFolder()
{
// Arrange
var path = @".";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.Empty(plugins);
}
}
}
``` |
ebb55fb2-204d-4ceb-9d3e-12943fbd9c99 | {
"language": "C#"
} | ```c#
using System;
using Npgsql;
namespace Dotnet.Microservice.Health.Checks
{
public class PostgresqlHealthCheck
{
/// <summary>
/// Check that a connection can be established to Postgresql and return the server version
/// </summary>
/// <param name="connectionString">An Npgsql connection string</param>
/// <returns>A <see cref="HealthResponse"/> object that contains the return status of this health check</returns>
public static HealthResponse CheckHealth(string connectionString)
{
try
{
NpgsqlConnection conn = new NpgsqlConnection(connectionString);
conn.Open();
string host = conn.Host;
string version = conn.PostgreSqlVersion.ToString();
int port = conn.Port;
conn.Close();
conn.Dispose();
return HealthResponse.Healthy(new { host = host, port = port , version = version});
}
catch (Exception e)
{
return HealthResponse.Unhealthy(e);
}
}
}
}
```
Clear connection pool so that an actual connection is created always | ```c#
using System;
using Npgsql;
namespace Dotnet.Microservice.Health.Checks
{
public class PostgresqlHealthCheck
{
/// <summary>
/// Check that a connection can be established to Postgresql and return the server version
/// </summary>
/// <param name="connectionString">An Npgsql connection string</param>
/// <returns>A <see cref="HealthResponse"/> object that contains the return status of this health check</returns>
public static HealthResponse CheckHealth(string connectionString)
{
try
{
NpgsqlConnection conn = new NpgsqlConnection(connectionString);
NpgsqlConnection.ClearPool(conn);
conn.Open();
string host = conn.Host;
string version = conn.PostgreSqlVersion.ToString();
int port = conn.Port;
conn.Close();
conn.Dispose();
return HealthResponse.Healthy(new { host = host, port = port , version = version});
}
catch (Exception e)
{
return HealthResponse.Unhealthy(e);
}
}
}
}
``` |
1699d15a-ee45-4463-966f-d3a82726c661 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Threading.Tasks;
using SocialToolBox.Core.Database;
using SocialToolBox.Core.Database.Projection;
using SocialToolBox.Core.Database.Serialization;
namespace SocialToolBox.Core.Mocks.Database.Projections
{
/// <summary>
/// An in-memory implementation of <see cref="IWritableStore{T}"/>
/// </summary>
public class InMemoryStore<T> : IWritableStore<T> where T : class
{
public readonly Dictionary<Id, byte[]> Contents = new Dictionary<Id,byte[]>();
public IDatabaseDriver Driver { get; private set; }
public readonly UntypedSerializer Serializer;
public InMemoryStore(IDatabaseDriver driver)
{
Driver = driver;
Serializer = new UntypedSerializer(driver.TypeDictionary);
}
// ReSharper disable CSharpWarnings::CS1998
public async Task<T> Get(Id id, IReadCursor cursor)
// ReSharper restore CSharpWarnings::CS1998
{
byte[] value;
if (!Contents.TryGetValue(id, out value)) return null;
return Serializer.Unserialize<T>(value);
}
// ReSharper disable CSharpWarnings::CS1998
public async Task Set(Id id, T item, IProjectCursor cursor)
// ReSharper restore CSharpWarnings::CS1998
{
Contents.Remove(id);
if (item == null) return;
Contents.Add(id,Serializer.Serialize(item));
}
}
}
```
Use lock for in-memory store | ```c#
using System.Collections.Generic;
using System.Threading.Tasks;
using SocialToolBox.Core.Async;
using SocialToolBox.Core.Database;
using SocialToolBox.Core.Database.Projection;
using SocialToolBox.Core.Database.Serialization;
namespace SocialToolBox.Core.Mocks.Database.Projections
{
/// <summary>
/// An in-memory implementation of <see cref="IWritableStore{T}"/>
/// </summary>
public class InMemoryStore<T> : IWritableStore<T> where T : class
{
public readonly Dictionary<Id, byte[]> Contents = new Dictionary<Id,byte[]>();
public IDatabaseDriver Driver { get; private set; }
public readonly UntypedSerializer Serializer;
public InMemoryStore(IDatabaseDriver driver)
{
Driver = driver;
Serializer = new UntypedSerializer(driver.TypeDictionary);
}
/// <summary>
/// A lock for avoiding multi-thread collisions.
/// </summary>
private readonly AsyncLock _lock = new AsyncLock();
public async Task<T> Get(Id id, IReadCursor cursor)
{
byte[] value;
using (await _lock.Lock())
{
if (!Contents.TryGetValue(id, out value)) return null;
}
return Serializer.Unserialize<T>(value);
}
public async Task Set(Id id, T item, IProjectCursor cursor)
{
var bytes = item == null ? null : Serializer.Serialize(item);
using (await _lock.Lock())
{
Contents.Remove(id);
if (item == null) return;
Contents.Add(id, bytes);
}
}
}
}
``` |
8753d1e4-c562-4630-b66b-3644bab84055 | {
"language": "C#"
} | ```c#
#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
_versionContext.Git = GitVersion();
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
}
```
Allow to run build even if git repo informations are not available | ```c#
#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
try
{
_versionContext.Git = GitVersion();
}
catch
{
_versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion();
}
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
}
``` |
a2569d60-bf64-4eed-ad40-74006368bb02 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CertiPay.ACH")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CertiPay.ACH")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9b9b2436-3cbc-4b6a-8c68-fc1565a21dd7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Make internals visible to the test assembly | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CertiPay.ACH")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CertiPay.ACH")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9b9b2436-3cbc-4b6a-8c68-fc1565a21dd7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("CertiPay.ACH.Tests")]
``` |
489c9c07-584d-4e69-b938-32de3ff4d0a3 | {
"language": "C#"
} | ```c#
#if TFS2015u2
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.VisualStudio.Services.Location;
using Microsoft.VisualStudio.Services.Location.Server;
namespace Aggregator.Core.Extensions
{
public static class LocationServiceExtensions
{
[SuppressMessage("Maintainability", "S1172:Unused method parameters should be removed", Justification = "Required by original interface", Scope = "member", Target = "~M:Aggregator.Core.Extensions.LocationServiceExtensions.GetSelfReferenceUri(Microsoft.VisualStudio.Services.Location.Server.ILocationService,Microsoft.TeamFoundation.Framework.Server.IVssRequestContext,Microsoft.VisualStudio.Services.Location.AccessMapping)~System.Uri")]
public static Uri GetSelfReferenceUri(this ILocationService self, IVssRequestContext context, AccessMapping mapping)
{
string url = self.GetSelfReferenceUrl(context, self.GetDefaultAccessMapping(context));
return new Uri(url, UriKind.Absolute);
}
}
}
#endif```
Use th esupplied access mappign instead of looking it up a second time. | ```c#
#if TFS2015u2
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.VisualStudio.Services.Location;
using Microsoft.VisualStudio.Services.Location.Server;
namespace Aggregator.Core.Extensions
{
public static class LocationServiceExtensions
{
public static Uri GetSelfReferenceUri(this ILocationService self, IVssRequestContext context, AccessMapping mapping)
{
string url = self.GetSelfReferenceUrl(context, mapping);
return new Uri(url, UriKind.Absolute);
}
}
}
#endif``` |
995f79f3-5d15-4e02-bc4d-c48be22da14d | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.Rooms;
using osu.Game.Screens.OnlinePlay.Multiplayer.Match;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene
{
[SetUp]
public new void Setup() => Schedule(() =>
{
SelectedRoom.Value = new Room();
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = 50,
Child = new MultiplayerMatchFooter()
};
});
}
}
```
Fix incorrect clearing of room | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Screens.OnlinePlay.Multiplayer.Match;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene
{
[SetUp]
public new void Setup() => Schedule(() =>
{
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = 50,
Child = new MultiplayerMatchFooter()
};
});
}
}
``` |
5697bc28-6a5b-4e36-baf9-e4cdcb40e199 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
/// <summary>
/// Represents a media picker property editor.
/// </summary>
[DataEditor(
Constants.PropertyEditors.Aliases.MediaPicker,
EditorType.PropertyValue | EditorType.MacroParameter,
"Media Picker",
"mediapicker",
ValueType = ValueTypes.Text,
Group = Constants.PropertyEditors.Groups.Media,
Icon = Constants.Icons.MediaImage)]
public class MediaPickerPropertyEditor : DataEditor
{
/// <summary>
/// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class.
/// </summary>
public MediaPickerPropertyEditor(ILogger logger)
: base(logger)
{
}
/// <inheritdoc />
protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor();
protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute);
internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference
{
public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute)
{
}
public IEnumerable<UmbracoEntityReference> GetReferences(object value)
{
var asString = value is string str ? str : value?.ToString();
if (string.IsNullOrEmpty(asString)) yield break;
if (Udi.TryParse(asString, out var udi))
yield return new UmbracoEntityReference(udi);
}
}
}
}
```
Handle for multiple picked media relations | ```c#
using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
/// <summary>
/// Represents a media picker property editor.
/// </summary>
[DataEditor(
Constants.PropertyEditors.Aliases.MediaPicker,
EditorType.PropertyValue | EditorType.MacroParameter,
"Media Picker",
"mediapicker",
ValueType = ValueTypes.Text,
Group = Constants.PropertyEditors.Groups.Media,
Icon = Constants.Icons.MediaImage)]
public class MediaPickerPropertyEditor : DataEditor
{
/// <summary>
/// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class.
/// </summary>
public MediaPickerPropertyEditor(ILogger logger)
: base(logger)
{
}
/// <inheritdoc />
protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor();
protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute);
internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference
{
public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute)
{
}
public IEnumerable<UmbracoEntityReference> GetReferences(object value)
{
var asString = value is string str ? str : value?.ToString();
if (string.IsNullOrEmpty(asString)) yield break;
foreach (var udiStr in asString.Split(','))
{
if (Udi.TryParse(udiStr, out var udi))
yield return new UmbracoEntityReference(udi);
}
}
}
}
}
``` |
8a570a69-177e-4211-aeae-e5695715c598 | {
"language": "C#"
} | ```c#
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using System.Linq;
using Windows.UI.Xaml.Controls;
namespace ArcGISRuntimeSDKDotNet_StoreSamples.Samples
{
/// <summary>
///
/// </summary>
/// <category>Mapping</category>
public sealed partial class OverviewMap : Page
{
public OverviewMap()
{
this.InitializeComponent();
mapView1.Map.InitialViewpoint = new Viewpoint(new Envelope(-5, 20, 50, 65, SpatialReferences.Wgs84));
}
private void mapView1_ExtentChanged(object sender, System.EventArgs e)
{
var graphicslayer = overviewMap.Map.Layers.OfType<GraphicsLayer>().FirstOrDefault();
Graphic g = graphicslayer.Graphics.FirstOrDefault();
if (g == null) //first time
{
g = new Graphic();
graphicslayer.Graphics.Add(g);
}
g.Geometry = mapView1.Extent;
}
}
}
```
Adjust the MapOverView map scale | ```c#
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using System.Linq;
using Windows.UI.Xaml.Controls;
namespace ArcGISRuntimeSDKDotNet_StoreSamples.Samples
{
/// <summary>
///
/// </summary>
/// <category>Mapping</category>
public sealed partial class OverviewMap : Page
{
public OverviewMap()
{
this.InitializeComponent();
mapView1.Map.InitialViewpoint = new Viewpoint(new Envelope(-5, 20, 50, 65, SpatialReferences.Wgs84));
}
private async void mapView1_ExtentChanged(object sender, System.EventArgs e)
{
var graphicslayer = overviewMap.Map.Layers.OfType<GraphicsLayer>().FirstOrDefault();
Graphic g = graphicslayer.Graphics.FirstOrDefault();
if (g == null) //first time
{
g = new Graphic();
graphicslayer.Graphics.Add(g);
}
g.Geometry = mapView1.Extent;
// Adjust overview map scale
await overviewMap.SetViewAsync(mapView1.Extent.GetCenter(), mapView1.Scale * 15);
}
}
}
``` |
b64b66ae-9eca-46ef-9754-ebbfbe665f78 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Containers;
namespace osu.Game.Screens.Edit.Setup
{
public class SetupScreen : EditorRoundedScreen
{
[Cached]
private SectionsContainer<SetupSection> sections = new SectionsContainer<SetupSection>();
[Cached]
private SetupScreenHeader header = new SetupScreenHeader();
public SetupScreen()
: base(EditorScreenMode.SongSetup)
{
}
[BackgroundDependencyLoader]
private void load()
{
AddRange(new Drawable[]
{
sections = new SectionsContainer<SetupSection>
{
FixedHeader = header,
RelativeSizeAxes = Axes.Both,
Children = new SetupSection[]
{
new ResourcesSection(),
new MetadataSection(),
new DifficultySection(),
new ColoursSection(),
new DesignSection(),
}
},
});
}
}
}
```
Fix pixels poking out of the top edge of editor setup screen | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Containers;
namespace osu.Game.Screens.Edit.Setup
{
public class SetupScreen : EditorRoundedScreen
{
[Cached]
private SectionsContainer<SetupSection> sections = new SectionsContainer<SetupSection>();
[Cached]
private SetupScreenHeader header = new SetupScreenHeader();
public SetupScreen()
: base(EditorScreenMode.SongSetup)
{
}
[BackgroundDependencyLoader]
private void load()
{
AddRange(new Drawable[]
{
sections = new SetupScreenSectionsContainer
{
FixedHeader = header,
RelativeSizeAxes = Axes.Both,
Children = new SetupSection[]
{
new ResourcesSection(),
new MetadataSection(),
new DifficultySection(),
new ColoursSection(),
new DesignSection(),
}
},
});
}
private class SetupScreenSectionsContainer : SectionsContainer<SetupSection>
{
protected override UserTrackingScrollContainer CreateScrollContainer()
{
var scrollContainer = base.CreateScrollContainer();
// Workaround for masking issues (see https://github.com/ppy/osu-framework/issues/1675#issuecomment-910023157)
// Note that this actually causes the full scroll range to be reduced by 2px at the bottom, but it's not really noticeable.
scrollContainer.Margin = new MarginPadding { Top = 2 };
return scrollContainer;
}
}
}
}
``` |
17641b60-6d4d-44d4-b402-e9e0c9731313 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Mitternacht;
using System.Threading.Tasks;
namespace MitternachtWeb {
public class Program {
public static async Task Main(string[] args) {
await new MitternachtBot(0, 0).RunAsync(args);
await CreateHostBuilder(args).Build().RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}
}
```
Move MitternachtBot instance to a static variable. | ```c#
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Mitternacht;
using System.Threading.Tasks;
namespace MitternachtWeb {
public class Program {
public static MitternachtBot MitternachtBot;
public static async Task Main(string[] args) {
MitternachtBot = new MitternachtBot(0, 0);
await MitternachtBot.RunAsync(args);
await CreateHostBuilder(args).Build().RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}
}
``` |
15e3c7d8-4396-495e-8342-124d2fe23e0c | {
"language": "C#"
} | ```c#
using HarryPotterUnity.Cards.BasicBehavior;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Quidditch.Items
{
[UsedImplicitly]
public class BluebottleBroom : ItemLessonProvider
{
public override void OnSelectedAction()
{
var card = Player.Discard.GetHealableCards(1);
Player.Discard.RemoveAll(card);
Player.Deck.AddAll(card);
Player.UseActions();
}
}
}
```
Add CanPerformAction condition to bluebottle broom | ```c#
using HarryPotterUnity.Cards.BasicBehavior;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Quidditch.Items
{
[UsedImplicitly]
public class BluebottleBroom : ItemLessonProvider
{
public override void OnSelectedAction()
{
var card = Player.Discard.GetHealableCards(1);
Player.Discard.RemoveAll(card);
Player.Deck.AddAll(card);
Player.UseActions();
}
public override bool CanPerformInPlayAction()
{
return Player.CanUseActions();
}
}
}
``` |
df9767fe-1fdb-48e8-a39d-1be27601b2ec | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Net.Http;
using Firestorm.Tests.Examples.Football.Web;
using Microsoft.AspNetCore.Hosting;
namespace Firestorm.Tests.Examples.Football.Tests
{
public class FootballTestFixture : IDisposable
{
private readonly IWebHost _host;
public HttpClient HttpClient { get; }
public FootballTestFixture()
{
var url = "http://localhost:1337";
_host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
//.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls(url)
.Build();
HttpClient = new HttpClient
{
BaseAddress = new Uri(url)
};
_host.Start();
}
public void Dispose()
{
_host.Dispose();
HttpClient.Dispose();
}
}
}```
Test fixture uses incrementing ports to avoid conflicts | ```c#
using System;
using System.IO;
using System.Net.Http;
using Firestorm.Tests.Examples.Football.Web;
using Microsoft.AspNetCore.Hosting;
namespace Firestorm.Tests.Examples.Football.Tests
{
public class FootballTestFixture : IDisposable
{
private static int _startPort = 3000;
private readonly IWebHost _host;
public HttpClient HttpClient { get; }
public FootballTestFixture()
{
var url = "http://localhost:" + _startPort++;
_host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
//.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls(url)
.Build();
HttpClient = new HttpClient
{
BaseAddress = new Uri(url)
};
_host.Start();
}
public void Dispose()
{
_host.Dispose();
HttpClient.Dispose();
}
}
}``` |
d910748a-34dc-4249-8613-773a45bdd3fe | {
"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 Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
/// <summary>
/// Helper class which provides <see cref="JsonSerializerSettings"/>.
/// </summary>
public static class JsonSerializerSettingsProvider
{
private const int DefaultMaxDepth = 32;
/// <summary>
/// Creates default <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <returns>Default <see cref="JsonSerializerSettings"/>.</returns>
public static JsonSerializerSettings CreateSerializerSettings()
{
return new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy(),
},
MissingMemberHandling = MissingMemberHandling.Ignore,
// Limit the object graph we'll consume to a fixed depth. This prevents stackoverflow exceptions
// from deserialization errors that might occur from deeply nested objects.
MaxDepth = DefaultMaxDepth,
// Do not change this setting
// Setting this to None prevents Json.NET from loading malicious, unsafe, or security-sensitive types
TypeNameHandling = TypeNameHandling.None,
};
}
}
}```
Return a shared contract resolver | ```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 Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
/// <summary>
/// Helper class which provides <see cref="JsonSerializerSettings"/>.
/// </summary>
public static class JsonSerializerSettingsProvider
{
private const int DefaultMaxDepth = 32;
// return shared resolver by default for perf so slow reflection logic is cached once
// developers can set their own resolver after the settings are returned if desired
private static readonly DefaultContractResolver SharedContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy(),
};
/// <summary>
/// Creates default <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <returns>Default <see cref="JsonSerializerSettings"/>.</returns>
public static JsonSerializerSettings CreateSerializerSettings()
{
return new JsonSerializerSettings
{
ContractResolver = SharedContractResolver,
MissingMemberHandling = MissingMemberHandling.Ignore,
// Limit the object graph we'll consume to a fixed depth. This prevents stackoverflow exceptions
// from deserialization errors that might occur from deeply nested objects.
MaxDepth = DefaultMaxDepth,
// Do not change this setting
// Setting this to None prevents Json.NET from loading malicious, unsafe, or security-sensitive types
TypeNameHandling = TypeNameHandling.None,
};
}
}
}
``` |
3e662598-24c9-46ec-a860-e5bdd23847dc | {
"language": "C#"
} | ```c#
using Utf8Json;
namespace Nest
{
internal class TypeNameFormatter : IJsonFormatter<TypeName>
{
public TypeName Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.GetCurrentJsonToken() == JsonToken.String)
{
TypeName typeName = reader.ReadString();
return typeName;
}
return null;
}
public void Serialize(ref JsonWriter writer, TypeName value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
var settings = formatterResolver.GetConnectionSettings();
var typeName = settings.Inferrer.TypeName(value);
writer.WriteString(typeName);
}
}
}
```
Allow TypeName to be used as Dictionary key | ```c#
using Utf8Json;
namespace Nest
{
internal class TypeNameFormatter : IJsonFormatter<TypeName>, IObjectPropertyNameFormatter<TypeName>
{
public TypeName Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.GetCurrentJsonToken() == JsonToken.String)
{
TypeName typeName = reader.ReadString();
return typeName;
}
reader.ReadNextBlock();
return null;
}
public void Serialize(ref JsonWriter writer, TypeName value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
var settings = formatterResolver.GetConnectionSettings();
var typeName = settings.Inferrer.TypeName(value);
writer.WriteString(typeName);
}
public void SerializeToPropertyName(ref JsonWriter writer, TypeName value, IJsonFormatterResolver formatterResolver) =>
Serialize(ref writer, value, formatterResolver);
public TypeName DeserializeFromPropertyName(ref JsonReader reader, IJsonFormatterResolver formatterResolver) =>
Deserialize(ref reader, formatterResolver);
}
}
``` |
255e412a-aa80-4fcc-91f7-f48e88484d3b | {
"language": "C#"
} | ```c#
namespace Tests
{
using System;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using JetBrains.Annotations;
using Tests.Properties;
using Xunit;
public class IntegrationTests
{
[NotNull]
private readonly Assembly _assembly;
public IntegrationTests()
{
var thisFolder = Path.GetDirectoryName(GetType().Assembly.Location);
_assembly = Assembly.LoadFrom(Path.Combine(thisFolder, "AssemblyToProcess.dll"));
}
[Fact]
public void CanCreateClass()
{
var type = _assembly.GetType("AssemblyToProcess.SimpleClass");
// ReSharper disable once AssignNullToNotNullAttribute
Activator.CreateInstance(type);
}
[Fact]
public void ReferenceIsRemoved()
{
// ReSharper disable once PossibleNullReferenceException
Assert.DoesNotContain(_assembly.GetReferencedAssemblies(), x => x.Name == "JetBrains.Annotations");
}
[Fact]
public void AreExternalAnnotationsCorrect()
{
var annotations = XDocument.Load(Path.ChangeExtension(_assembly.Location, ".ExternalAnnotations.xml")).ToString();
Assert.Equal(Resources.ExpectedAnnotations, annotations);
}
[Fact]
public void IsDocumentationProperlyDecorated()
{
var _documentation = XDocument.Load(Path.ChangeExtension(_assembly.Location, ".xml")).ToString();
Assert.Equal(Resources.ExpectedDocumentation, _documentation);
}
}
}```
Fix file location for build server | ```c#
namespace Tests
{
using System;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using JetBrains.Annotations;
using Tests.Properties;
using Xunit;
public class IntegrationTests
{
[NotNull]
private readonly string _targetFolder = AppDomain.CurrentDomain.BaseDirectory;
[NotNull]
private readonly Assembly _assembly;
public IntegrationTests()
{
_assembly = Assembly.LoadFrom(Path.Combine(_targetFolder, "AssemblyToProcess.dll"));
}
[Fact]
public void CanCreateClass()
{
var type = _assembly.GetType("AssemblyToProcess.SimpleClass");
// ReSharper disable once AssignNullToNotNullAttribute
Activator.CreateInstance(type);
}
[Fact]
public void ReferenceIsRemoved()
{
// ReSharper disable once PossibleNullReferenceException
Assert.DoesNotContain(_assembly.GetReferencedAssemblies(), x => x.Name == "JetBrains.Annotations");
}
[Fact]
public void AreExternalAnnotationsCorrect()
{
var annotations = XDocument.Load(Path.ChangeExtension(_targetFolder, ".ExternalAnnotations.xml")).ToString();
Assert.Equal(Resources.ExpectedAnnotations, annotations);
}
[Fact]
public void IsDocumentationProperlyDecorated()
{
var _documentation = XDocument.Load(Path.ChangeExtension(_targetFolder, ".xml")).ToString();
Assert.Equal(Resources.ExpectedDocumentation, _documentation);
}
}
}``` |
e6918b6b-fc43-42a3-95cf-0c21c1970d0d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Talks.C2DF.Interfaces;
namespace Talks.C2DF.Web.Controllers
{
public class HomeController: Controller
{
//ICostCalculator calculator;
//public HomeController(ICostCalculator calculator)
//{
// this.calculator = calculator;
//}
ISendingMicroApp sendingApp;
public HomeController(ISendingMicroApp sendingApp)
{
this.sendingApp = sendingApp;
}
public ActionResult Index()
{
var result = sendingApp.Send("Hello World!!!DEAL");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}```
Update Home Controller to send message - and log it | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Talks.C2DF.BetterApp.Lib.Logging;
using Talks.C2DF.Interfaces;
namespace Talks.C2DF.Web.Controllers
{
public class HomeController: Controller
{
ISendingMicroApp sendingApp;
IAppLogger _logger;
public HomeController(ISendingMicroApp sendingApp, IAppLogger logger)
{
this.sendingApp = sendingApp;
_logger = logger;
}
public ActionResult Index()
{
_logger.Debug("Sending Message from MVC App");
var result = sendingApp.Send("Hello World!!!DEAL");
_logger.Debug($"Result: {result.ResultMessage} -- Price: {result.Price} -- Message: {result.Message} ");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}``` |
0e1f8b95-358b-429d-93e3-50cadf92a598 | {
"language": "C#"
} | ```c#
using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel
{
public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction) : base("")
{
Transaction = transaction;
Title = $"Transaction ({transaction.TransactionId[0..10]}) Details";
}
public TransactionDetailsViewModel Transaction { get; }
}
}
```
Fix lurking wife mode on transaction id in details | ```c#
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
using Splat;
using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel
{
public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction) : base("")
{
Global = Locator.Current.GetService<Global>();
Transaction = transaction;
Title = $"Transaction ({transaction.TransactionId[0..10]}) Details";
}
public override void OnOpen(CompositeDisposable disposables)
{
Global.UiConfig.WhenAnyValue(x => x.LurkingWifeMode)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x => Transaction.RaisePropertyChanged(nameof(Transaction.TransactionId)))
.DisposeWith(disposables);
base.OnOpen(disposables);
}
protected Global Global { get; }
public TransactionDetailsViewModel Transaction { get; }
}
}
``` |
d3edbfcd-6067-45c7-a478-e6f8f1be699a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.DataFlow;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
[ShellComponent]
public class UnityTestsSpecificYamlFileExtensionMapping : IFileExtensionMapping
{
private static readonly string[] ourFileExtensions =
{
#if RIDER
// Rider doesn't register .yaml, as the frontend already provides support for it. But we need it for tests...
".yaml",
#endif
".meta",
".asset",
".unity"
};
public UnityTestsSpecificYamlFileExtensionMapping(Lifetime lifetime)
{
Changed = new SimpleSignal(lifetime, GetType().Name + "::Changed");
}
public IEnumerable<ProjectFileType> GetFileTypes(string extension)
{
if (ourFileExtensions.Contains(extension, StringComparer.InvariantCultureIgnoreCase))
return new[] {YamlProjectFileType.Instance};
return EmptyList<ProjectFileType>.Enumerable;
}
public IEnumerable<string> GetExtensions(ProjectFileType projectFileType)
{
if (Equals(projectFileType, YamlProjectFileType.Instance))
return ourFileExtensions;
return EmptyList<string>.Enumerable;
}
public ISimpleSignal Changed { get; }
}
}```
Fix breaking change in SDK | ```c#
using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
[ShellComponent]
public class UnityTestsSpecificYamlFileExtensionMapping : FileTypeDefinitionExtensionMapping
{
private static readonly string[] ourFileExtensions =
{
#if RIDER
// Rider doesn't register .yaml, as the frontend already provides support for it. But we need it for tests...
".yaml",
#endif
".meta",
".asset",
".unity"
};
public UnityTestsSpecificYamlFileExtensionMapping(Lifetime lifetime, IProjectFileTypes fileTypes)
: base(lifetime, fileTypes)
{
}
public override IEnumerable<ProjectFileType> GetFileTypes(string extension)
{
if (ourFileExtensions.Contains(extension, StringComparer.InvariantCultureIgnoreCase))
return new[] {YamlProjectFileType.Instance};
return EmptyList<ProjectFileType>.Enumerable;
}
public override IEnumerable<string> GetExtensions(ProjectFileType projectFileType)
{
if (Equals(projectFileType, YamlProjectFileType.Instance))
return ourFileExtensions;
return base.GetExtensions(projectFileType);
}
}
}``` |
e735f9e0-3e27-40bb-8475-5cd040dd2828 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace MultiMiner.Xgminer.Api.Parsers
{
class VersionInformationParser : ResponseTextParser
{
public static void ParseTextForVersionInformation(string text, MultiMiner.Xgminer.Api.Data.VersionInformation versionInformation)
{
List<string> responseParts = text.Split('|').ToList();
Dictionary<string, string> keyValuePairs = GetDictionaryFromTextChunk(responseParts[0]);
versionInformation.Name = keyValuePairs["Msg"].Replace(" versions", String.Empty);
versionInformation.Description = keyValuePairs["Description"];
keyValuePairs = GetDictionaryFromTextChunk(responseParts[1]);
versionInformation.MinerVersion = keyValuePairs["CGMiner"];
versionInformation.ApiVersion = keyValuePairs["API"];
}
}
}
```
Work around incomatibility in SGMiner 4.0 with the CGMiner RPC API | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace MultiMiner.Xgminer.Api.Parsers
{
class VersionInformationParser : ResponseTextParser
{
public static void ParseTextForVersionInformation(string text, MultiMiner.Xgminer.Api.Data.VersionInformation versionInformation)
{
List<string> responseParts = text.Split('|').ToList();
Dictionary<string, string> keyValuePairs = GetDictionaryFromTextChunk(responseParts[0]);
versionInformation.Name = keyValuePairs["Msg"].Replace(" versions", String.Empty);
versionInformation.Description = keyValuePairs["Description"];
keyValuePairs = GetDictionaryFromTextChunk(responseParts[1]);
string key = "CGMiner";
if (keyValuePairs.ContainsKey(key))
versionInformation.MinerVersion = keyValuePairs[key];
else
{
// SGMiner 4.0 broke compatibility with the CGMiner RPC API
// Version 5.0 fixed the issue - this work-around is for 4.0
// Request :"version"
// Response:"STATUS=S,When=1415068731,Code=22,Msg=SGMiner versions,Description=sgminer 4.1.0|VERSION,SGMiner=4.1.0,API=3.1|\u0000"
key = "SGMiner";
if (keyValuePairs.ContainsKey(key))
versionInformation.MinerVersion = keyValuePairs[key];
}
versionInformation.ApiVersion = keyValuePairs["API"];
}
}
}
``` |
113e5078-1ca6-4003-9403-1084cb4cd52c | {
"language": "C#"
} | ```c#
using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace DeviceHive.Setup.Actions
{
class SqlDatabaseValidator
{
private SqlConnection _connection;
public SqlDatabaseValidator(SqlConnection connection)
{
if (connection == null)
throw new ArgumentNullException("connection");
_connection = connection;
}
public void Validate(string databaseName)
{
if (databaseName == null)
throw new ArgumentNullException("databaseName");
string sqlCommand = string.Format("SELECT CASE WHEN db_id('{0}') is null THEN 0 ELSE 1 END", databaseName);
IDbCommand command = new SqlCommand(sqlCommand, _connection);
if (!Convert.ToBoolean(command.ExecuteScalar()))
throw new Exception(string.Format("Database '{0}' does not exist. Please enter a correct database name.", databaseName));
}
}
}
```
Check database name input parameter | ```c#
using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace DeviceHive.Setup.Actions
{
class SqlDatabaseValidator
{
private SqlConnection _connection;
public SqlDatabaseValidator(SqlConnection connection)
{
if (connection == null)
throw new ArgumentNullException("connection");
_connection = connection;
}
public void Validate(string databaseName)
{
if (string.IsNullOrEmpty(databaseName))
throw new ArgumentNullException("databaseName");
string sqlCommand = string.Format("SELECT CASE WHEN db_id('{0}') is null THEN 0 ELSE 1 END", databaseName);
IDbCommand command = new SqlCommand(sqlCommand, _connection);
if (!Convert.ToBoolean(command.ExecuteScalar()))
throw new Exception(string.Format("Database '{0}' does not exist. Please enter a correct database name.", databaseName));
}
}
}
``` |
276d6d57-9f1c-43c7-a2fd-f8025f039698 | {
"language": "C#"
} | ```c#
//
// MonoTouch defines for docfixer
//
using System;
using System.IO;
using System.Reflection;
using MonoTouch.Foundation;
public partial class DocGenerator {
static Assembly assembly = typeof (MonoTouch.Foundation.NSObject).Assembly;
const string BaseNamespace = "MonoTouch";
static string GetMostRecentDocBase ()
{
var versions = new[]{"4_0", "3_2", "3_1"};
string format = "/Developer/Platforms/iPhoneOS.platform/Developer/Documentation/DocSets/com.apple.adc.documentation.AppleiPhone{0}.iPhoneLibrary.docset/Contents/Resources/Documents/documentation";
foreach (var v in versions) {
var d = string.Format (format, v);
if (Directory.Exists (d)) {
return d;
break;
}
}
return null;
}
public static string GetSelector (object attr)
{
return ((ExportAttribute) attr).Selector;
}
}```
Fix docfixed to work with iOS5 | ```c#
//
// MonoTouch defines for docfixer
//
using System;
using System.IO;
using System.Reflection;
using MonoTouch.Foundation;
public partial class DocGenerator {
static Assembly assembly = typeof (MonoTouch.Foundation.NSObject).Assembly;
const string BaseNamespace = "MonoTouch";
static string GetMostRecentDocBase ()
{
//var versions = new[]{"4_0", "3_2", "3_1"};
//string format = "/Developer/Platforms/iPhoneOS.platform/Developer/Documentation/DocSets/com.apple.adc.documentation.AppleiPhone{0}.iPhoneLibrary.docset/Contents/Resources/Documents/documentation";
var versions = new [] { "5_0" };
string format = "/Library/Developer/Documentation/DocSets/com.apple.adc.documentation.AppleiOS{0}.iOSLibrary.docset/Contents/Resources/Documents/documentation";
foreach (var v in versions) {
var d = string.Format (format, v);
if (Directory.Exists (d)) {
return d;
break;
}
}
return null;
}
public static string GetSelector (object attr)
{
return ((ExportAttribute) attr).Selector;
}
}``` |
6b5c687e-7a0a-43d7-b196-7f64e921bb1d | {
"language": "C#"
} | ```c#
using JetBrains.ReSharper.FeaturesTestFramework.Intentions;
using JetBrains.ReSharper.Intentions.CSharp.QuickFixes;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;
namespace XmlDocInspections.Plugin.Tests.Integrative
{
[TestFixture]
[TestNetFramework4]
public class AddDocCommentFixTest : CSharpQuickFixTestBase<AddDocCommentFix>
{
protected override string RelativeTestDataPath => @"QuickFixes\AddDocCommentFix";
[Test]
public void TestClass()
{
DoNamedTest2();
}
[Test]
public void TestSimpleMethod()
{
DoNamedTest2();
}
[Test]
public void TestMethodWithAdditionalElementsForDocTemplate()
{
DoNamedTest2();
}
[Test]
public void TestField()
{
DoNamedTest2();
}
[Test]
public void TestProperty()
{
DoNamedTest2();
}
}
}
```
Refactor to expr. bodied members | ```c#
using JetBrains.ReSharper.FeaturesTestFramework.Intentions;
using JetBrains.ReSharper.Intentions.CSharp.QuickFixes;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;
namespace XmlDocInspections.Plugin.Tests.Integrative
{
[TestFixture]
[TestNetFramework4]
public class AddDocCommentFixTest : CSharpQuickFixTestBase<AddDocCommentFix>
{
protected override string RelativeTestDataPath => @"QuickFixes\AddDocCommentFix";
[Test]
public void TestClass() => DoNamedTest2();
[Test]
public void TestSimpleMethod() => DoNamedTest2();
[Test]
public void TestMethodWithAdditionalElementsForDocTemplate() => DoNamedTest2();
[Test]
public void TestField() => DoNamedTest2();
[Test]
public void TestProperty() => DoNamedTest2();
}
}
``` |
d39b3e17-4a00-4d16-93cf-eceaf4c33f7d | {
"language": "C#"
} | ```c#
using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.EAS.Domain.Data.Repositories;
using SFA.DAS.EAS.Domain.Models.UserProfile;
using SFA.DAS.Sql.Client;
using SFA.DAS.NLog.Logger;
namespace SFA.DAS.EAS.Infrastructure.Data
{
public class UserRepository : BaseRepository, IUserRepository
{
private readonly Lazy<EmployerAccountsDbContext> _db;
public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db)
: base(configuration.DatabaseConnectionString, logger)
{
_db = db;
}
public Task Upsert(User user)
{
return WithConnection(c =>
{
var parameters = new DynamicParameters();
parameters.Add("@email", user.Email, DbType.String);
parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid);
parameters.Add("@firstName", user.FirstName, DbType.String);
parameters.Add("@lastName", user.LastName, DbType.String);
return c.ExecuteAsync(
sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName",
param: parameters,
commandType: CommandType.Text);
});
}
}
}```
Add correlationId to fix startup of the EAS web application. Copied from specific branch | ```c#
using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.EAS.Domain.Data.Repositories;
using SFA.DAS.EAS.Domain.Models.UserProfile;
using SFA.DAS.Sql.Client;
using SFA.DAS.NLog.Logger;
namespace SFA.DAS.EAS.Infrastructure.Data
{
public class UserRepository : BaseRepository, IUserRepository
{
private readonly Lazy<EmployerAccountsDbContext> _db;
public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db)
: base(configuration.DatabaseConnectionString, logger)
{
_db = db;
}
public Task Upsert(User user)
{
return WithConnection(c =>
{
var parameters = new DynamicParameters();
parameters.Add("@email", user.Email, DbType.String);
parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid);
parameters.Add("@firstName", user.FirstName, DbType.String);
parameters.Add("@lastName", user.LastName, DbType.String);
parameters.Add("@correlationId", null, DbType.String);
return c.ExecuteAsync(
sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName, @correlationId",
param: parameters,
commandType: CommandType.Text);
});
}
}
}``` |
7b0a7976-327e-4c3f-b43e-b6d63dbdad3f | {
"language": "C#"
} | ```c#
using Amazon.Lambda.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.APIGatewayEvents;
namespace Amazon.Lambda.AspNetCoreServer
{
/// <summary>
/// Helper extensions for APIGatewayProxyFunction
/// </summary>
public static class APIGatewayProxyFunctionExtensions
{
/// <summary>
/// An overload of FunctionHandlerAsync to allow working with the typed API Gateway event classes. Implemented as an extension
/// method to avoid confusion of using it as the function handler for the Lambda function.
/// </summary>
/// <param name="function"></param>
/// <param name="request"></param>
/// <param name="lambdaContext"></param>
/// <returns></returns>
public static async Task<APIGatewayProxyResponse> FunctionHandlerAsync(this APIGatewayProxyFunction function, APIGatewayProxyRequest request, ILambdaContext lambdaContext)
{
ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();
var requestStream = new MemoryStream();
serializer.Serialize<APIGatewayProxyRequest>(request, requestStream);
requestStream.Position = 0;
var responseStream = await function.FunctionHandlerAsync(requestStream, lambdaContext);
var response = serializer.Deserialize<APIGatewayProxyResponse>(responseStream);
return response;
}
}
}
```
Change namespace for helper extension method to Amazon.Lambda.TestUtilities to make it more discover able when writing tests. | ```c#
using Amazon.Lambda.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.AspNetCoreServer;
namespace Amazon.Lambda.TestUtilities
{
/// <summary>
/// Extension methods for APIGatewayProxyFunction to make it easier to write tests
/// </summary>
public static class APIGatewayProxyFunctionExtensions
{
/// <summary>
/// An overload of FunctionHandlerAsync to allow working with the typed API Gateway event classes. Implemented as an extension
/// method to avoid confusion of using it as the function handler for the Lambda function.
/// </summary>
/// <param name="function"></param>
/// <param name="request"></param>
/// <param name="lambdaContext"></param>
/// <returns></returns>
public static async Task<APIGatewayProxyResponse> FunctionHandlerAsync(this APIGatewayProxyFunction function, APIGatewayProxyRequest request, ILambdaContext lambdaContext)
{
ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();
var requestStream = new MemoryStream();
serializer.Serialize<APIGatewayProxyRequest>(request, requestStream);
requestStream.Position = 0;
var responseStream = await function.FunctionHandlerAsync(requestStream, lambdaContext);
var response = serializer.Deserialize<APIGatewayProxyResponse>(responseStream);
return response;
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.