doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
2e92b66a-b577-4a3e-ba60-484c6dc13b8b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Core.CrossDomainImagesWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
{
//set access token in hidden field for client calls
hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;
//set images
Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
Services.ImgService svc = new Services.ImgService();
Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
}
}
}
}```
Revert "Revert "added try catch, test commit"" | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Core.CrossDomainImagesWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
{
//set access token in hidden field for client calls
hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;
//set images
Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
Services.ImgService svc = new Services.ImgService();
Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
}
}
catch (Exception)
{
throw;
}
}
}
}``` |
0be03f5f-c04e-4b7c-8ef9-8f5d158d7732 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Mitternacht.Modules.Games.Common;
using Mitternacht.Services;
namespace Mitternacht.Modules.Games.Services {
public class GamesService : IMService {
private readonly IBotConfigProvider _bc;
public readonly ConcurrentDictionary<ulong, GirlRating> GirlRatings = new ConcurrentDictionary<ulong, GirlRating>();
public readonly ImmutableArray<string> EightBallResponses;
public readonly string TypingArticlesPath = "data/typing_articles2.json";
public GamesService(IBotConfigProvider bc) {
_bc = bc;
EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();
var timer = new Timer(_ => {
GirlRatings.Clear();
}, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));
}
}
}
```
Rename field to better match type. | ```c#
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Mitternacht.Modules.Games.Common;
using Mitternacht.Services;
namespace Mitternacht.Modules.Games.Services {
public class GamesService : IMService {
private readonly IBotConfigProvider _bcp;
public readonly ConcurrentDictionary<ulong, GirlRating> GirlRatings = new ConcurrentDictionary<ulong, GirlRating>();
public readonly ImmutableArray<string> EightBallResponses;
public readonly string TypingArticlesPath = "data/typing_articles2.json";
public GamesService(IBotConfigProvider bcp) {
_bcp = bcp;
EightBallResponses = _bcp.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();
var timer = new Timer(_ => {
GirlRatings.Clear();
}, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));
}
}
}
``` |
559fe2d7-6fb2-414d-865f-19c5a1005e77 | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
namespace NuGet {
public static class ExceptionUtility {
public static Exception Unwrap(Exception exception) {
if (exception == null) {
throw new ArgumentNullException("exception");
}
if (exception.InnerException == null) {
return exception;
}
// Always return the inner exception from a target invocation exception
if (exception.GetType() == typeof(TargetInvocationException)) {
return exception.InnerException;
}
// Flatten the aggregate before getting the inner exception
if (exception.GetType() == typeof(AggregateException)) {
return ((AggregateException)exception).Flatten().InnerException;
}
return exception;
}
}
}
```
Call GetBaseException instead of manually unwrapping exception types. | ```c#
using System;
using System.Reflection;
namespace NuGet {
public static class ExceptionUtility {
public static Exception Unwrap(Exception exception) {
if (exception == null) {
throw new ArgumentNullException("exception");
}
if (exception.InnerException == null) {
return exception;
}
// Always return the inner exception from a target invocation exception
if (exception is AggregateException ||
exception is TargetInvocationException) {
return exception.GetBaseException();
}
return exception;
}
}
}
``` |
d1580601-1c54-48b4-ab0a-b3b52b1fd0b7 | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;
public static class SharpLabObjectExtensions {
// LinqPad/etc compatibility only
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Dump<T>(this T value)
=> value.Inspect(title: "Dump");
public static void Inspect<T>(this T value, string title = "Inspect") {
var builder = new StringBuilder();
ObjectAppender.Append(builder, value);
var data = new SimpleInspectionResult(title, builder);
Output.Write(data);
}
}
```
Return value in Dump ext. method. | ```c#
using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;
public static class SharpLabObjectExtensions {
// LinqPad/etc compatibility only
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Dump<T>(this T value) {
value.Inspect(title: "Dump");
return value;
}
public static void Inspect<T>(this T value, string title = "Inspect") {
var builder = new StringBuilder();
ObjectAppender.Append(builder, value);
var data = new SimpleInspectionResult(title, builder);
Output.Write(data);
}
}
``` |
e96c858f-8942-4462-b474-6c81311d4894 | {
"language": "C#"
} | ```c#
using Alensia.Core.Input;
using UnityEngine.Assertions;
namespace Alensia.Core.Locomotion
{
public abstract class LocomotionControl<T> : Control.Control, ILocomotionControl<T>
where T : class, ILocomotion
{
public T Locomotion { get; }
public override bool Valid => base.Valid && Locomotion.Active;
protected LocomotionControl(T locomotion, IInputManager inputManager) : base(inputManager)
{
Assert.IsNotNull(locomotion, "locomotion != null");
Locomotion = locomotion;
}
}
}```
Allow overriding of locomotion implementation | ```c#
using Alensia.Core.Input;
namespace Alensia.Core.Locomotion
{
public abstract class LocomotionControl<T> : Control.Control, ILocomotionControl<T>
where T : class, ILocomotion
{
public abstract T Locomotion { get; }
public override bool Valid => base.Valid && Locomotion != null && Locomotion.Active;
protected LocomotionControl(IInputManager inputManager) : base(inputManager)
{
}
}
}``` |
fb9b1c8b-816a-4af6-84fe-d4b02ea31d44 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ArcMapAddinVisibility
{
public class MapPointTool : ESRI.ArcGIS.Desktop.AddIns.Tool
{
public MapPointTool()
{
}
protected override void OnUpdate()
{
Enabled = ArcMap.Application != null;
}
}
}
```
Implement Map Point Tool Mouse events | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ArcMapAddinVisibility.Helpers;
namespace ArcMapAddinVisibility
{
public class MapPointTool : ESRI.ArcGIS.Desktop.AddIns.Tool
{
public MapPointTool()
{
}
protected override void OnUpdate()
{
Enabled = ArcMap.Application != null;
}
protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
{
if (arg.Button != System.Windows.Forms.MouseButtons.Left)
return;
try
{
//Get the active view from the ArcMap static class.
IActiveView activeView = ArcMap.Document.FocusMap as IActiveView;
var point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint;
Mediator.NotifyColleagues(Constants.NEW_MAP_POINT, point);
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
protected override void OnMouseMove(MouseEventArgs arg)
{
IActiveView activeView = ArcMap.Document.FocusMap as IActiveView;
var point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint;
Mediator.NotifyColleagues(Constants.MOUSE_MOVE_POINT, point);
}
}
}
``` |
97bf4ac3-0ff1-452f-a9bf-2c0bc952cee7 | {
"language": "C#"
} | ```c#
using System;
namespace AppHarbor.Commands
{
public class AddConfigCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
public AddConfigCommand(IApplicationConfiguration applicationConfiguration)
{
_applicationConfiguration = applicationConfiguration;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
```
Initialize AppConfigCommand with an IAppHarborClient | ```c#
using System;
namespace AppHarbor.Commands
{
public class AddConfigCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
private readonly IAppHarborClient _appharborClient;
public AddConfigCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient)
{
_applicationConfiguration = applicationConfiguration;
_appharborClient = appharborClient;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
``` |
6ed4d720-dd9e-429a-b0c9-7f9af0fdda90 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DocFunctions.Lib.Models.Github
{
public abstract class AbstractAction
{
public string FullFilename { get; set; }
public string CommitSha { get; set; }
public string CommitShaForRead { get; set; }
public string Path
{
get
{
if (FullFilename.Contains("/"))
{
return FullFilename.Replace("/" + Filename, "");
}
else
{
return FullFilename.Replace(Filename, "");
}
}
}
public string Filename
{
get
{
return System.IO.Path.GetFileName(FullFilename);
}
}
public bool IsBlogFile
{
get
{
return (Extension == ".md" || Extension == ".json");
}
}
public bool IsImageFile
{
get
{
return (Extension == ".png" || Extension == ".jpg" || Extension == ".gif");
}
}
private string Extension
{
get
{
return System.IO.Path.GetExtension(FullFilename);
}
}
}
}
```
Fix for filename lowercase matches - to fix missing .PNG images | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DocFunctions.Lib.Models.Github
{
public abstract class AbstractAction
{
public string FullFilename { get; set; }
public string CommitSha { get; set; }
public string CommitShaForRead { get; set; }
public string Path
{
get
{
if (FullFilename.Contains("/"))
{
return FullFilename.Replace("/" + Filename, "");
}
else
{
return FullFilename.Replace(Filename, "");
}
}
}
public string Filename
{
get
{
return System.IO.Path.GetFileName(FullFilename);
}
}
public bool IsBlogFile
{
get
{
return (Extension.ToLower() == ".md" || Extension.ToLower() == ".json");
}
}
public bool IsImageFile
{
get
{
return (Extension.ToLower() == ".png" || Extension.ToLower() == ".jpg" || Extension.ToLower() == ".gif");
}
}
private string Extension
{
get
{
return System.IO.Path.GetExtension(FullFilename);
}
}
}
}
``` |
3590452f-de08-4fa8-b07c-e148e6f34097 | {
"language": "C#"
} | ```c#
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
/// <content>
/// Contains the <see cref="FindFirstFileExFlags"/> nested enum.
/// </content>
public partial class Kernel32
{
/// <summary>
/// Optional flags to pass to the <see cref="FindFirstFileEx"/> method.
/// </summary>
[Flags]
public enum FindFirstFileExFlags
{
/// <summary>
/// Searches are case-sensitive.
/// </summary>
CaseSensitive,
/// <summary>
/// Uses a larger buffer for directory queries, which can increase performance of the find operation.
/// </summary>
LargeFetch,
}
}
}
```
Apply fixes to duplicate file | ```c#
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
/// <content>
/// Contains the <see cref="FindFirstFileExFlags"/> nested enum.
/// </content>
public partial class Kernel32
{
/// <summary>
/// Optional flags to pass to the <see cref="FindFirstFileEx"/> method.
/// </summary>
[Flags]
public enum FindFirstFileExFlags
{
/// <summary>
/// No flags.
/// </summary>
None = 0x0,
/// <summary>
/// Searches are case-sensitive.
/// </summary>
CaseSensitive = 0x1,
/// <summary>
/// Uses a larger buffer for directory queries, which can increase performance of the find operation.
/// </summary>
LargeFetch = 0x2,
}
}
}
``` |
1fee02e7-81d5-49ad-83a6-b5d8e36197ae | {
"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.
//
namespace Test
{
using System;
struct AA
{
static float[] m_afStatic1;
static void Main1()
{
ulong[] param2 = new ulong[10];
uint[] local5 = new uint[7];
try
{
try
{
int[] local8 = new int[7];
try
{
//.......
}
catch (Exception)
{
do
{
//.......
} while (m_afStatic1[233] > 0.0);
}
while (0 != local5[205])
return;
}
catch (IndexOutOfRangeException)
{
float[] local10 = new float[7];
while ((int)param2[168] != 1)
{
float[] local11 = new float[7];
}
}
}
catch (NullReferenceException) { }
}
static int Main()
{
try
{
Main1();
return -1;
}
catch (IndexOutOfRangeException)
{
return 100;
}
}
}
}
```
Disable test failing on VS2015 | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Test
{
using System;
struct AA
{
static float[] m_afStatic1;
static void Main1()
{
ulong[] param2 = new ulong[10];
uint[] local5 = new uint[7];
try
{
try
{
int[] local8 = new int[7];
try
{
//.......
}
catch (Exception)
{
do
{
//.......
} while (m_afStatic1[233] > 0.0);
}
while (0 != local5[205])
return;
}
catch (IndexOutOfRangeException)
{
float[] local10 = new float[7];
while ((int)param2[168] != 1)
{
float[] local11 = new float[7];
}
}
}
catch (NullReferenceException) { }
}
static int Main()
{
try
{
// Issue #1421 RyuJIT generates incorrect exception handling scopes for IL generated by Roslyn
#if false
Main1();
return -1;
#endif
return 100;
}
catch (IndexOutOfRangeException)
{
return 100;
}
}
}
}
``` |
e544789f-754b-4008-9f0e-85e6d0b55e52 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AndreasBittner : IAmACommunityMember
{
public string FirstName => "Andreas";
public string LastName => "Bittner";
public string ShortBioOrTagLine => "DevOp and MCSE Server 2012R2";
public string StateOrRegion => "Saxony, Germany";
public string EmailAddress => "";
public string TwitterHandle => "Andreas_Bittner";
public string GitHubHandle => "bobruhny";
public string GravatarHash => "9e94e1e9014ad138df3f5281f814d755";
public GeoPosition Position => new GeoPosition(49,4833, 10,7167);
public Uri WebSite => new Uri("http://joinpowershell.de/de/new/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri(""); } }
}
}```
Add RSS Infomation for Andreas Bittner | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AndreasBittner : IAmACommunityMember
{
public string FirstName => "Andreas";
public string LastName => "Bittner";
public string ShortBioOrTagLine => "DevOp and MCSE Server 2012R2";
public string StateOrRegion => "Saxony, Germany";
public string EmailAddress => "";
public string TwitterHandle => "Andreas_Bittner";
public string GitHubHandle => "bobruhny";
public string GravatarHash => "9e94e1e9014ad138df3f5281f814d755";
public GeoPosition Position => new GeoPosition(49,4833, 10,7167);
public Uri WebSite => new Uri("http://joinpowershell.de/de/new/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://joinpowershell.de/de/feed/"); } }
}
}``` |
9f0d96ce-df38-4218-ba33-32c99e4f7709 | {
"language": "C#"
} | ```c#
using System.Runtime.InteropServices;
using System.Windows;
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
```
Set UI exe assembly title | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
[assembly: AssemblyTitle("Certify The Web (UI)")]
``` |
28c6bb7b-3fd7-460e-a962-7cce73bb07fa | {
"language": "C#"
} | ```c#
using StackExchange.Elastic;
namespace StackExchange.Opserver
{
public class OpserverCore
{
// Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
public static void Init()
{
try
{
ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
// We're going to get errors - that's kinda the point of monitoring
// No need to log every one here unless for crazy debugging
//ElasticException.ExceptionOccurred += e => Current.LogException(e);
}
catch { }
}
}
}
```
Enable TLS 1.1 and 1.2 and disable SSLv3 for external calls. | ```c#
using System.Net;
using StackExchange.Elastic;
namespace StackExchange.Opserver
{
public class OpserverCore
{
// Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
public static void Init()
{
try
{
ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
// We're going to get errors - that's kinda the point of monitoring
// No need to log every one here unless for crazy debugging
//ElasticException.ExceptionOccurred += e => Current.LogException(e);
}
catch { }
// Enable TLS only for SSL negotiation, SSL has been broken for some time.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
}
}
}
``` |
734f9383-4b17-446a-8290-7868861da9ce | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Mirage.Urbanization.WinForms
{
public abstract class ToolstripMenuInitializer<TOption>
where TOption : IToolstripMenuOption
{
protected ToolstripMenuInitializer(ToolStripMenuItem targetToopToolStripMenuItem, IEnumerable<TOption> options)
{
foreach (var option in options)
{
var localOption = option;
var item = new ToolStripMenuItem(option.Name);
item.Click += (sender, e) =>
{
foreach (var x in targetToopToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>())
x.Checked = false;
item.Checked = true;
_currentOption = localOption;
if (OnSelectionChanged != null)
OnSelectionChanged(this, new ToolstripMenuOptionChangedEventArgs<TOption>(_currentOption));
};
targetToopToolStripMenuItem.DropDownItems.Add(item);
item.PerformClick();
}
}
public event EventHandler<ToolstripMenuOptionChangedEventArgs<TOption>> OnSelectionChanged;
private TOption _currentOption;
public TOption GetCurrentOption() { return _currentOption; }
}
}```
Implement unconditional toggle of the first item when a toolstrip menu is initialized. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Mirage.Urbanization.WinForms
{
public abstract class ToolstripMenuInitializer<TOption>
where TOption : IToolstripMenuOption
{
protected ToolstripMenuInitializer(ToolStripMenuItem targetToopToolStripMenuItem, IEnumerable<TOption> options)
{
ToolStripMenuItem first = null;
foreach (var option in options)
{
var localOption = option;
var item = new ToolStripMenuItem(option.Name);
item.Click += (sender, e) =>
{
foreach (var x in targetToopToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>())
x.Checked = false;
item.Checked = true;
_currentOption = localOption;
if (OnSelectionChanged != null)
OnSelectionChanged(this, new ToolstripMenuOptionChangedEventArgs<TOption>(_currentOption));
};
targetToopToolStripMenuItem.DropDownItems.Add(item);
if (first == null)
first = item;
}
first.PerformClick();
}
public event EventHandler<ToolstripMenuOptionChangedEventArgs<TOption>> OnSelectionChanged;
private TOption _currentOption;
public TOption GetCurrentOption() { return _currentOption; }
}
}``` |
88e17743-5fca-4000-ae84-ae76b0aecdb9 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")]
[assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")]
[assembly: AssemblyProduct("Affecto.IdentityManagement")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("8.0.3.0")]
[assembly: AssemblyFileVersion("8.0.3.0")]
// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("8.0.3")]```
Raise store mocking project version. | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")]
[assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")]
[assembly: AssemblyProduct("Affecto.IdentityManagement")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("8.0.4.0")]
[assembly: AssemblyFileVersion("8.0.4.0")]
// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("8.0.4-prerelease01")]``` |
b7c6723b-29e1-4c34-a64e-19d0855cca00 | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using UnityEngine;
namespace Finegamedesign.Utils
{
/// <summary>
/// Wrapper of logging.
/// Conditionally compiles if in debug mode or editor.
/// </summary>
public sealed class DebugUtil
{
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void Log(string message)
{
UnityEngine.Debug.Log(message);
}
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void LogWarning(string message)
{
UnityEngine.Debug.LogWarning(message);
}
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void Assert(bool condition, string message = "")
{
UnityEngine.Debug.Assert(condition, message);
}
}
}
```
Debug Util: Wraps log error. | ```c#
using System.Diagnostics;
using UnityEngine;
namespace Finegamedesign.Utils
{
/// <summary>
/// Wrapper of logging.
/// Conditionally compiles if in debug mode or editor.
/// </summary>
public sealed class DebugUtil
{
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void Log(string message)
{
UnityEngine.Debug.Log(message);
}
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void LogWarning(string message)
{
UnityEngine.Debug.LogWarning(message);
}
public static void LogError(string message)
{
UnityEngine.Debug.LogError(message);
}
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void Assert(bool condition, string message = "")
{
UnityEngine.Debug.Assert(condition, message);
}
}
}
``` |
a41be644-0d19-4bd0-abba-16461f839cd0 | {
"language": "C#"
} | ```c#
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.3.0";
}
}
```
Update file version to 3.0.4.0 | ```c#
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.4.0";
}
}
``` |
b0c602e8-0b01-4575-b195-b0802e0279e9 | {
"language": "C#"
} | ```c#
using System;
using System.Xml.Serialization;
namespace XeroApi.Model
{
public class ManualJournal : ModelBase
{
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
[ItemId]
public Guid ManualJournalID { get; set; }
public DateTime? Date { get; set; }
public string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public string Narration { get; set; }
[XmlArrayItem("JournalLine")]
public ManualJournalLineItems JournalLines { get; set; }
}
public class ManualJournals : ModelList<ManualJournal>
{
}
}```
Add optional Url and ShowOnCashBasisReports fields for MJs | ```c#
using System;
using System.Xml.Serialization;
namespace XeroApi.Model
{
public class ManualJournal : ModelBase
{
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
[ItemId]
public Guid ManualJournalID { get; set; }
public DateTime? Date { get; set; }
public string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public string Narration { get; set; }
public string Url { get; set; }
public bool? ShowOnCashBasisReports { get; set; }
[XmlArrayItem("JournalLine")]
public ManualJournalLineItems JournalLines { get; set; }
}
public class ManualJournals : ModelList<ManualJournal>
{
}
}``` |
16696b9c-c2be-4fd8-8a4d-250f5f6db24a | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Security;
using System.Security.Principal;
namespace System
{
internal static class EnvironmentHelpers
{
private static volatile bool s_isAppContainerProcess;
private static volatile bool s_isAppContainerProcessInitalized;
internal const int TokenIsAppContainer = 29;
public static bool IsAppContainerProcess
{
get
{
if (!s_isAppContainerProcessInitalized)
{
s_isAppContainerProcess = HasAppContainerToken();
s_isAppContainerProcessInitalized = true;
}
return s_isAppContainerProcess;
}
}
[SecuritySafeCritical]
private static unsafe bool HasAppContainerToken()
{
int* dwIsAppContainerPtr = stackalloc int[1];
uint dwLength = 0;
using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query))
{
if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength))
{
throw new Win32Exception();
}
}
return (*dwIsAppContainerPtr != 0);
}
}
}
```
Fix IsAppContainerProcess for Windows 7 | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Security;
using System.Security.Principal;
namespace System
{
internal static class EnvironmentHelpers
{
private static volatile bool s_isAppContainerProcess;
private static volatile bool s_isAppContainerProcessInitalized;
internal const int TokenIsAppContainer = 29;
public static bool IsAppContainerProcess
{
get
{
if(!s_IsAppContainerProcessInitalized) {
if(Environment.OSVersion.Platform != PlatformID.Win32NT) {
s_IsAppContainerProcess = false;
} else if(Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1)) {
// Windows 7 or older.
s_IsAppContainerProcess = false;
} else {
s_IsAppContainerProcess = HasAppContainerToken();
}
s_IsAppContainerProcessInitalized = true;
}
return s_IsAppContainerProcess;
}
}
[SecuritySafeCritical]
private static unsafe bool HasAppContainerToken()
{
int* dwIsAppContainerPtr = stackalloc int[1];
uint dwLength = 0;
using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query))
{
if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength))
{
throw new Win32Exception();
}
}
return (*dwIsAppContainerPtr != 0);
}
}
}
``` |
cc0352f5-4796-4c60-a631-6e0c29e24281 | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Xml.Linq;
using WebDav.Helpers;
namespace WebDav.Request
{
internal static class PropfindRequestBuilder
{
public static string BuildRequestBody(string[] customProperties)
{
XNamespace webDavNs = "DAV:";
var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
var propfind = new XElement(webDavNs + "propfind", new XAttribute(XNamespace.Xmlns + "D", webDavNs));
propfind.Add(new XElement(webDavNs + "allprop"));
if (customProperties.Any())
{
var include = new XElement(webDavNs + "include");
foreach (var prop in customProperties)
{
include.Add(new XElement(webDavNs + prop));
}
propfind.Add(include);
}
doc.Add(propfind);
return doc.ToStringWithDeclaration();
}
}
}
```
Use standard syntax to build propfind requests | ```c#
using System.Linq;
using System.Xml.Linq;
using WebDav.Helpers;
namespace WebDav.Request
{
internal static class PropfindRequestBuilder
{
public static string BuildRequestBody(string[] customProperties)
{
var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
var propfind = new XElement("{DAV:}propfind", new XAttribute(XNamespace.Xmlns + "D", "DAV:"));
propfind.Add(new XElement("{DAV:}allprop"));
if (customProperties.Any())
{
var include = new XElement("{DAV:}include");
foreach (var prop in customProperties)
{
include.Add(new XElement(XName.Get(prop, "DAV:")));
}
propfind.Add(include);
}
doc.Add(propfind);
return doc.ToStringWithDeclaration();
}
}
}
``` |
704b8227-ac92-416a-adf3-bb932d486125 | {
"language": "C#"
} | ```c#
using MaterialColor.Common.Data;
using System.Collections.Generic;
using UnityEngine;
namespace MaterialColor.Core
{
public static class State
{
public static Dictionary<string, Color32> TypeColorOffsets = new Dictionary<string, Color32>();
public static Dictionary<SimHashes, ElementColorInfo> ElementColorInfos = new Dictionary<SimHashes, ElementColorInfo>();
public static ConfiguratorState ConfiguratorState = new ConfiguratorState();
public static bool Disabled = false;
public static readonly List<string> TileNames = new List<string>
{
"Tile", "MeshTile", "InsulationTile", "GasPermeableMembrane"
};
}
}
```
Add TilePOI to list of tile names | ```c#
using MaterialColor.Common.Data;
using System.Collections.Generic;
using UnityEngine;
namespace MaterialColor.Core
{
public static class State
{
public static Dictionary<string, Color32> TypeColorOffsets = new Dictionary<string, Color32>();
public static Dictionary<SimHashes, ElementColorInfo> ElementColorInfos = new Dictionary<SimHashes, ElementColorInfo>();
public static ConfiguratorState ConfiguratorState = new ConfiguratorState();
public static bool Disabled = false;
public static readonly List<string> TileNames = new List<string>
{
"Tile", "MeshTile", "InsulationTile", "GasPermeableMembrane", "TilePOI"
};
}
}
``` |
d5fbb82a-4f53-4721-ad69-390d2bd4af71 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings.Sections.Audio
{
public class OffsetSettings : SettingsSubsection
{
protected override LocalisableString Header => "Offset Adjustment";
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsSlider<double, OffsetSlider>
{
LabelText = "Audio offset",
Current = config.GetBindable<double>(OsuSetting.AudioOffset),
KeyboardStep = 1f
},
new SettingsButton
{
Text = "Offset wizard"
}
};
}
private class OffsetSlider : OsuSliderBar<double>
{
public override LocalisableString TooltipText => Current.Value.ToString(@"0ms");
}
}
}
```
Add keywords to make finding audio offset adjustments easier in settings | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings.Sections.Audio
{
public class OffsetSettings : SettingsSubsection
{
protected override LocalisableString Header => "Offset Adjustment";
public override IEnumerable<string> FilterTerms => base.FilterTerms.Concat(new[] { "universal", "uo", "timing" });
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsSlider<double, OffsetSlider>
{
LabelText = "Audio offset",
Current = config.GetBindable<double>(OsuSetting.AudioOffset),
KeyboardStep = 1f
},
new SettingsButton
{
Text = "Offset wizard"
}
};
}
private class OffsetSlider : OsuSliderBar<double>
{
public override LocalisableString TooltipText => Current.Value.ToString(@"0ms");
}
}
}
``` |
88edacdf-4289-41dd-8032-a27ec872b654 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.Deployment.WindowsInstaller;
namespace Wix.CustomActions
{
using System.IO;
public class CustomActions
{
[CustomAction]
public static ActionResult CloseIt(Session session)
{
try
{
const string fileFullPath = @"c:\KensCustomAction.txt";
if (!File.Exists(fileFullPath))
File.Create(fileFullPath);
File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now));
session.Log("Close DotTray!");
}
catch (Exception ex)
{
session.Log("ERROR in custom action CloseIt {0}", ex.ToString());
return ActionResult.Failure;
}
return ActionResult.Success;
}
}
}
```
Add more logic to the custom action. | ```c#
using System;
using Microsoft.Deployment.WindowsInstaller;
namespace Wix.CustomActions
{
using System.IO;
using System.Diagnostics;
public class CustomActions
{
[CustomAction]
public static ActionResult CloseIt(Session session)
{
try
{
Debugger.Launch();
const string fileFullPath = @"c:\KensCustomAction.txt";
if (!File.Exists(fileFullPath))
File.Create(fileFullPath);
File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now));
session.Log("Close DotTray!");
}
catch (Exception ex)
{
session.Log("ERROR in custom action CloseIt {0}", ex.ToString());
return ActionResult.Failure;
}
return ActionResult.Success;
}
}
}
``` |
43e01445-01b7-4361-8205-8cbe7675b78a | {
"language": "C#"
} | ```c#
namespace FlatFile.FixedLength.Attributes.Infrastructure
{
using System;
using System.Linq;
using FlatFile.Core;
using FlatFile.Core.Attributes.Extensions;
using FlatFile.Core.Attributes.Infrastructure;
using FlatFile.Core.Base;
public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
{
public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
{
var container = new FieldsContainer<FixedFieldSettings>();
var fileMappingType = typeof(T);
var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();
if (fileAttribute == null)
{
throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
fileMappingType.Name,
typeof(FixedLengthFileAttribute).Name));
}
var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();
foreach (var p in properties)
{
var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;
if (attribute != null)
{
var fieldSettings = attribute.GetFieldSettings(p.Property);
container.AddOrUpdate(fieldSettings, false);
}
}
var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container);
return descriptor;
}
}
}```
Fix header behavior for the fixed length types | ```c#
namespace FlatFile.FixedLength.Attributes.Infrastructure
{
using System;
using System.Linq;
using FlatFile.Core;
using FlatFile.Core.Attributes.Extensions;
using FlatFile.Core.Attributes.Infrastructure;
using FlatFile.Core.Base;
public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
{
public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
{
var container = new FieldsContainer<FixedFieldSettings>();
var fileMappingType = typeof(T);
var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();
if (fileAttribute == null)
{
throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
fileMappingType.Name,
typeof(FixedLengthFileAttribute).Name));
}
var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();
foreach (var p in properties)
{
var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;
if (attribute != null)
{
var fieldSettings = attribute.GetFieldSettings(p.Property);
container.AddOrUpdate(fieldSettings, false);
}
}
var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container)
{
HasHeader = false
};
return descriptor;
}
}
}``` |
8b989845-be64-4206-8440-450cf8dff705 | {
"language": "C#"
} | ```c#
using UnityEngine;
namespace com.adjust.sdk.test
{
public class TestFactoryAndroid : ITestFactory
{
private string _baseUrl;
private AndroidJavaObject ajoTestLibrary;
private CommandListenerAndroid onCommandReceivedListener;
public TestFactoryAndroid(string baseUrl)
{
_baseUrl = baseUrl;
CommandExecutor commandExecutor = new CommandExecutor(this, baseUrl);
onCommandReceivedListener = new CommandListenerAndroid(commandExecutor);
}
public void StartTestSession()
{
TestApp.Log("TestFactory -> StartTestSession()");
if (ajoTestLibrary == null)
{
ajoTestLibrary = new AndroidJavaObject(
"com.adjust.testlibrary.TestLibrary",
_baseUrl,
onCommandReceivedListener);
}
TestApp.Log("TestFactory -> calling testLib.startTestSession()");
ajoTestLibrary.Call("startTestSession", TestApp.CLIENT_SDK);
}
public void AddInfoToSend(string key, string paramValue)
{
if (ajoTestLibrary == null)
{
return;
}
ajoTestLibrary.Call("addInfoToSend", key, paramValue);
}
public void SendInfoToServer(string basePath)
{
if (ajoTestLibrary == null)
{
return;
}
ajoTestLibrary.Call("sendInfoToServer", basePath);
}
public void AddTest(string testName)
{
if (ajoTestLibrary == null) {
return;
}
ajoTestLibrary.Call("addTest", testName);
}
public void AddTestDirectory(string testDirectory)
{
if (ajoTestLibrary == null)
{
return;
}
ajoTestLibrary.Call("addTestDirectory", testDirectory);
}
}
}
```
Initialize android test library on contructor | ```c#
using UnityEngine;
namespace com.adjust.sdk.test
{
public class TestFactoryAndroid : ITestFactory
{
private string _baseUrl;
private AndroidJavaObject ajoTestLibrary;
private CommandListenerAndroid onCommandReceivedListener;
public TestFactoryAndroid(string baseUrl)
{
_baseUrl = baseUrl;
CommandExecutor commandExecutor = new CommandExecutor(this, baseUrl);
onCommandReceivedListener = new CommandListenerAndroid(commandExecutor);
ajoTestLibrary = new AndroidJavaObject(
"com.adjust.testlibrary.TestLibrary",
_baseUrl,
onCommandReceivedListener);
}
public void StartTestSession()
{
ajoTestLibrary.Call("startTestSession", TestApp.CLIENT_SDK);
}
public void AddInfoToSend(string key, string paramValue)
{
ajoTestLibrary.Call("addInfoToSend", key, paramValue);
}
public void SendInfoToServer(string basePath)
{
ajoTestLibrary.Call("sendInfoToServer", basePath);
}
public void AddTest(string testName)
{
ajoTestLibrary.Call("addTest", testName);
}
public void AddTestDirectory(string testDirectory)
{
ajoTestLibrary.Call("addTestDirectory", testDirectory);
}
}
}
``` |
b47c082a-fb98-47e4-80f6-0ffb719e0c2c | {
"language": "C#"
} | ```c#
#addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Default"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Default").Does (() =>
{
const string sln = "./../Vibrate.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Default")
.Does (() =>
{
NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
});
});
RunTarget (TARGET);
```
Adjust output directory in script | ```c#
#addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Default"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Default").Does (() =>
{
const string sln = "./../Vibrate.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Default")
.Does (() =>
{
NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./../",
BasePath = "./",
});
});
RunTarget (TARGET);
``` |
f620476e-93ef-447a-960f-c6f093ec5e56 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace CertiPay.Payroll.Common
{
/// <summary>
/// Describes how an employee pay is calculated
/// </summary>
public enum EmployeePayType : byte
{
/// <summary>
/// Employee earns a set salary per period of time, i.e. $70,000 yearly
/// </summary>
Salary = 1,
/// <summary>
/// Employee earns a given amount per hour of work, i.e. $10 per hour
/// </summary>
Hourly = 2
}
public static class EmployeePayTypes
{
public static IEnumerable<EmployeePayType> Values()
{
yield return EmployeePayType.Salary;
yield return EmployeePayType.Hourly;
}
}
}```
Add commission as Employee Pay Type | ```c#
using System.Collections.Generic;
namespace CertiPay.Payroll.Common
{
/// <summary>
/// Describes how an employee pay is calculated
/// </summary>
public enum EmployeePayType : byte
{
/// <summary>
/// Employee earns a set salary per period of time, i.e. $70,000 yearly
/// </summary>
Salary = 1,
/// <summary>
/// Employee earns a given amount per hour of work, i.e. $10 per hour
/// </summary>
Hourly = 2,
/// <summary>
/// Employee earns a flat rate based on sales or project completion
/// </summary>
Commission = 3
}
public static class EmployeePayTypes
{
public static IEnumerable<EmployeePayType> Values()
{
yield return EmployeePayType.Salary;
yield return EmployeePayType.Hourly;
yield return EmployeePayType.Commission;
}
}
}``` |
19eebc4e-089e-45e5-ac44-754301bcee82 | {
"language": "C#"
} | ```c#
using System.Web.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;
using ValidateRequestExample.Filters;
namespace ValidateRequestExample.Controllers
{
public class IncomingController : TwilioController
{
[ValidateTwilioRequest]
public ActionResult Voice(string from)
{
var response = new TwilioResponse();
const string message = "Thanks for calling! " +
"Your phone number is {0}. I got your call because of Twilio's webhook. " +
"Goodbye!";
response.Say(string.Format(message, from));
response.Hangup();
return TwiML(response);
}
[ValidateTwilioRequest]
public ActionResult Message(string body)
{
var response = new TwilioResponse();
response.Say($"Your text to me was {body.Length} characters long. Webhooks are neat :)");
response.Hangup();
return TwiML(response);
}
}
}
```
Update controller for request validation | ```c#
using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;
using ValidateRequestExample.Filters;
namespace ValidateRequestExample.Controllers
{
public class IncomingController : TwilioController
{
[ValidateTwilioRequest]
public ActionResult Voice(string from)
{
var message = "Thanks for calling! " +
$"Your phone number is {from}. " +
"I got your call because of Twilio's webhook. " +
"Goodbye!";
var response = new VoiceResponse();
response.Say(string.Format(message, from));
response.Hangup();
return TwiML(response);
}
[ValidateTwilioRequest]
public ActionResult Message(string body)
{
var message = $"Your text to me was {body.Length} characters long. " +
"Webhooks are neat :)";
var response = new MessagingResponse();
response.Message(new Message(message));
return TwiML(response);
}
}
}
``` |
7be82118-0406-4ae6-9480-f40721bad03c | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
using DevTyr.Gullap;
namespace DevTyr.Gullap.Tests.With_Guard.For_NotNullOrEmpty
{
[TestFixture]
public class When_argument_is_not_null
{
[Test]
public void Should_pass ()
{
Guard.NotNullOrEmpty ("", null);
Assert.Pass ();
}
}
}
```
Fix test for NotNullOrEmpty passing check. | ```c#
using System;
using NUnit.Framework;
using DevTyr.Gullap;
namespace DevTyr.Gullap.Tests.With_Guard.For_NotNullOrEmpty
{
[TestFixture]
public class When_argument_is_not_null_or_empty
{
[Test]
public void Should_pass ()
{
Guard.NotNullOrEmpty ("Test", null);
Assert.Pass ();
}
}
}
``` |
dc4de48f-1447-4688-a596-0e24225c55da | {
"language": "C#"
} | ```c#
using BankService.Domain.Contracts;
using BankService.Domain.Models;
using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
namespace BankService.Api.Controllers
{
[EnableCors("MyPolicy")]
[Route("api/accountHolders")]
public class AccountHolderController : Controller
{
private readonly IAccountHolderRepository accountHolderRepository;
private readonly ICachedAccountHolderRepository cachedAccountHolderRepository;
public AccountHolderController(IAccountHolderRepository repository, ICachedAccountHolderRepository cachedRepository)
{
this.accountHolderRepository = repository;
this.cachedAccountHolderRepository = cachedRepository;
}
[HttpGet]
public IEnumerable<AccountHolder> Get()
{
return this.accountHolderRepository.GetWithLimit(100);
}
[HttpGet("{id}")]
public AccountHolder Get(string id)
{
var accountHolder = this.cachedAccountHolderRepository.Get(id);
if (accountHolder != null)
{
return accountHolder;
}
accountHolder = this.accountHolderRepository.GetById(id);
this.cachedAccountHolderRepository.Set(accountHolder);
return accountHolder;
}
}
}
```
Remove EnableCors attribute from controller | ```c#
using BankService.Domain.Contracts;
using BankService.Domain.Models;
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
namespace BankService.Api.Controllers
{
[Route("api/accountHolders")]
public class AccountHolderController : Controller
{
private readonly IAccountHolderRepository accountHolderRepository;
private readonly ICachedAccountHolderRepository cachedAccountHolderRepository;
public AccountHolderController(IAccountHolderRepository repository, ICachedAccountHolderRepository cachedRepository)
{
this.accountHolderRepository = repository;
this.cachedAccountHolderRepository = cachedRepository;
}
[HttpGet]
public IEnumerable<AccountHolder> Get()
{
return this.accountHolderRepository.GetWithLimit(100);
}
[HttpGet("{id}")]
public AccountHolder Get(string id)
{
var accountHolder = this.cachedAccountHolderRepository.Get(id);
if (accountHolder != null)
{
return accountHolder;
}
accountHolder = this.accountHolderRepository.GetById(id);
this.cachedAccountHolderRepository.Set(accountHolder);
return accountHolder;
}
}
}
``` |
4bda1243-9f2a-436a-b17d-c2172c5c1a33 | {
"language": "C#"
} | ```c#
namespace VotingSystem.Web.Areas.User.ViewModels
{
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using VotingSystem.Models;
using VotingSystem.Web.Infrastructure.Mapping;
using AutoMapper;
public class UserPollsViewModel : IMapFrom<Poll>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[HiddenInput(DisplayValue = false)]
public string Author { get; set; }
public bool IsPublic { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string UserId { get; set; }
public void CreateMappings(AutoMapper.IConfiguration configuration)
{
configuration.CreateMap<Poll, UserPollsViewModel>()
.ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
}
}
}```
Hide UserId by Editing in KendoGrid PopUp | ```c#
namespace VotingSystem.Web.Areas.User.ViewModels
{
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using VotingSystem.Models;
using VotingSystem.Web.Infrastructure.Mapping;
using AutoMapper;
public class UserPollsViewModel : IMapFrom<Poll>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[HiddenInput(DisplayValue = false)]
public string Author { get; set; }
public bool IsPublic { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[HiddenInput(DisplayValue = false)]
public string UserId { get; set; }
public void CreateMappings(AutoMapper.IConfiguration configuration)
{
configuration.CreateMap<Poll, UserPollsViewModel>()
.ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
}
}
}``` |
223aba09-9cd7-4574-8e53-c45a1a475913 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.DX11.Internals.Effects.Pins;
using VVVV.PluginInterfaces.V2;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using VVVV.Hosting.Pins;
using VVVV.DX11.Lib.Effects.Pins;
using FeralTic.DX11;
namespace VVVV.DX11.Internals.Effects.Pins
{
public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription>
{
private SamplerState state;
protected override void ProcessAttribute(InputAttribute attr, EffectVariable var)
{
attr.IsSingle = true;
attr.CheckIfChanged = true;
}
protected override bool RecreatePin(EffectVariable var)
{
return false;
}
public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
{
if (this.pin.PluginIO.IsConnected)
{
using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice]))
{
shaderinstance.SetByName(this.Name, state);
}
}
else
{
shaderinstance.Effect.GetVariableByName(this.Name).AsConstantBuffer().UndoSetConstantBuffer();
}
}
}
}```
Fix error in sampler state pin connection | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.DX11.Internals.Effects.Pins;
using VVVV.PluginInterfaces.V2;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using VVVV.Hosting.Pins;
using VVVV.DX11.Lib.Effects.Pins;
using FeralTic.DX11;
namespace VVVV.DX11.Internals.Effects.Pins
{
public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription>
{
private SamplerState state;
protected override void ProcessAttribute(InputAttribute attr, EffectVariable var)
{
attr.IsSingle = true;
attr.CheckIfChanged = true;
}
protected override bool RecreatePin(EffectVariable var)
{
return false;
}
public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
{
if (this.pin.PluginIO.IsConnected)
{
using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice]))
{
shaderinstance.SetByName(this.Name, state);
}
}
else
{
shaderinstance.Effect.GetVariableByName(this.Name).AsSampler().UndoSetSamplerState(0);
}
}
}
}``` |
33d310ae-f0ea-49be-8580-e0e4e713890e | {
"language": "C#"
} | ```c#
using Harvest.Net.Models;
using System;
using System.Linq;
using Xunit;
namespace Harvest.Net.Tests
{
public class TimeTrackingFacts : FactBase, IDisposable
{
DayEntry _todelete = null;
[Fact]
public void Daily_ReturnsResult()
{
var result = Api.Daily();
Assert.NotNull(result);
Assert.NotNull(result.DayEntries);
Assert.NotNull(result.Projects);
Assert.Equal(DateTime.Now.Date, result.ForDay);
}
[Fact]
public void Daily_ReturnsCorrectResult()
{
var result = Api.Daily(286857409);
Assert.NotNull(result);
Assert.Equal(1m, result.DayEntry.Hours);
Assert.Equal(new DateTime(2014, 12, 19), result.DayEntry.SpentAt);
}
[Fact]
public void CreateDaily_CreatesAnEntry()
{
var result = Api.CreateDaily(DateTime.Now.Date, GetTestId(TestId.ProjectId), GetTestId(TestId.TaskId), 2);
_todelete = result.DayEntry;
Assert.Equal(2m, result.DayEntry.Hours);
Assert.Equal(GetTestId(TestId.ProjectId), result.DayEntry.ProjectId);
Assert.Equal(GetTestId(TestId.TaskId), result.DayEntry.TaskId);
}
public void Dispose()
{
if (_todelete != null)
Api.DeleteDaily(_todelete.Id);
}
}
}
```
Fix test to work in any timezone | ```c#
using Harvest.Net.Models;
using System;
using System.Linq;
using Xunit;
namespace Harvest.Net.Tests
{
public class TimeTrackingFacts : FactBase, IDisposable
{
DayEntry _todelete = null;
[Fact]
public void Daily_ReturnsResult()
{
var result = Api.Daily();
Assert.NotNull(result);
Assert.NotNull(result.DayEntries);
Assert.NotNull(result.Projects);
// The test harvest account is in EST, but Travis CI runs in different timezones
Assert.Equal(TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")).Date, result.ForDay);
}
[Fact]
public void Daily_ReturnsCorrectResult()
{
var result = Api.Daily(286857409);
Assert.NotNull(result);
Assert.Equal(1m, result.DayEntry.Hours);
Assert.Equal(new DateTime(2014, 12, 19), result.DayEntry.SpentAt);
}
[Fact]
public void CreateDaily_CreatesAnEntry()
{
var result = Api.CreateDaily(DateTime.Now.Date, GetTestId(TestId.ProjectId), GetTestId(TestId.TaskId), 2);
_todelete = result.DayEntry;
Assert.Equal(2m, result.DayEntry.Hours);
Assert.Equal(GetTestId(TestId.ProjectId), result.DayEntry.ProjectId);
Assert.Equal(GetTestId(TestId.TaskId), result.DayEntry.TaskId);
}
public void Dispose()
{
if (_todelete != null)
Api.DeleteDaily(_todelete.Id);
}
}
}
``` |
493ecdeb-aa0f-40ee-87cd-3615c0977481 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;
using ProtoBuf.Meta;
namespace Infrastructure
{
public class ProtobufOutputFormatter : OutputFormatter
{
private static Lazy<RuntimeTypeModel> model = new Lazy<RuntimeTypeModel>(CreateTypeModel);
public string ContentType { get; private set; }
public static RuntimeTypeModel Model
{
get { return model.Value; }
}
public ProtobufOutputFormatter()
{
ContentType = "application/x-protobuf";
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/x-protobuf"));
//SupportedEncodings.Add(Encoding.GetEncoding("utf-8"));
}
private static RuntimeTypeModel CreateTypeModel()
{
var typeModel = TypeModel.Create();
typeModel.UseImplicitZeroDefaults = false;
return typeModel;
}
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
var response = context.HttpContext.Response;
Model.Serialize(response.Body, context.Object);
return Task.FromResult(response);
}
}
}```
Add encoding header to protobuf content | ```c#
using System;
using Microsoft.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;
using ProtoBuf.Meta;
namespace Infrastructure
{
public class ProtobufOutputFormatter : OutputFormatter
{
private static Lazy<RuntimeTypeModel> model = new Lazy<RuntimeTypeModel>(CreateTypeModel);
public string ContentType { get; private set; }
public static RuntimeTypeModel Model
{
get { return model.Value; }
}
public ProtobufOutputFormatter()
{
ContentType = "application/x-protobuf";
var mediaTypeHeader = MediaTypeHeaderValue.Parse(ContentType);
mediaTypeHeader.Encoding = System.Text.Encoding.UTF8;
SupportedMediaTypes.Add(mediaTypeHeader);
}
private static RuntimeTypeModel CreateTypeModel()
{
var typeModel = TypeModel.Create();
typeModel.UseImplicitZeroDefaults = false;
return typeModel;
}
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
var response = context.HttpContext.Response;
Model.Serialize(response.Body, context.Object);
return Task.FromResult(response);
}
}
}``` |
596e6168-9834-4348-80ff-5a0eb5eeda08 | {
"language": "C#"
} | ```c#
using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using System.Text;
namespace Abp.AspNetCore.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason
{
get
{
if (OverridedValue != null)
{
return OverridedValue.Reason;
}
// TODO: Use back HttpContextAccessor.HttpContext?.Request.GetDisplayUrl()
// after moved to net core 3.0
// see https://github.com/aspnet/AspNetCore/issues/2718#issuecomment-482347489
return GetDisplayUrl(HttpContextAccessor.HttpContext?.Request);
}
}
protected IHttpContextAccessor HttpContextAccessor { get; }
private const string SchemeDelimiter = "://";
public HttpRequestEntityChangeSetReasonProvider(
IHttpContextAccessor httpContextAccessor,
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
HttpContextAccessor = httpContextAccessor;
}
private string GetDisplayUrl(HttpRequest request)
{
if (request == null)
{
Logger.Debug("Unable to get URL from HttpRequest, fallback to null");
return null;
}
var scheme = request.Scheme ?? string.Empty;
var host = request.Host.Value ?? string.Empty;
var pathBase = request.PathBase.Value ?? string.Empty;
var path = request.Path.Value ?? string.Empty;
var queryString = request.QueryString.Value ?? string.Empty;
// PERF: Calculate string length to allocate correct buffer size for StringBuilder.
var length = scheme.Length + SchemeDelimiter.Length + host.Length
+ pathBase.Length + path.Length + queryString.Length;
return new StringBuilder(length)
.Append(scheme)
.Append(SchemeDelimiter)
.Append(host)
.Append(pathBase)
.Append(path)
.Append(queryString)
.ToString();
}
}
}
```
Use the aspnet core built-in GetDisplayUrl method. | ```c#
using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using System.Text;
using Microsoft.AspNetCore.Http.Extensions;
namespace Abp.AspNetCore.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason => OverridedValue != null
? OverridedValue.Reason
: HttpContextAccessor.HttpContext?.Request.GetDisplayUrl();
protected IHttpContextAccessor HttpContextAccessor { get; }
private const string SchemeDelimiter = "://";
public HttpRequestEntityChangeSetReasonProvider(
IHttpContextAccessor httpContextAccessor,
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
HttpContextAccessor = httpContextAccessor;
}
}
}
``` |
6cdfafb1-c82d-417f-89fb-ca6975e95e29 | {
"language": "C#"
} | ```c#
using System;
using System.Data.Entity;
using PhotoLife.Data.Contracts;
namespace PhotoLife.Data
{
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext dbContext;
public UnitOfWork(DbContext context)
{
if (context == null)
{
throw new ArgumentNullException("Context cannot be null");
}
this.dbContext = context;
}
public void Dispose()
{
}
public void Commit()
{
this.dbContext.SaveChanges();
}
}
}
```
Fix unit of work ctor param | ```c#
using System;
using PhotoLife.Data.Contracts;
namespace PhotoLife.Data
{
public class UnitOfWork : IUnitOfWork
{
private readonly IPhotoLifeEntities dbContext;
public UnitOfWork(IPhotoLifeEntities context)
{
if (context == null)
{
throw new ArgumentNullException("Context cannot be null");
}
this.dbContext = context;
}
public void Dispose()
{
}
public void Commit()
{
this.dbContext.SaveChanges();
}
}
}
``` |
e7a15c0a-3642-435e-bc23-68383724c192 | {
"language": "C#"
} | ```c#
namespace Worker.Scalable
{
using King.Service;
using System.Diagnostics;
using System.Threading.Tasks;
public class ScalableTask : IDynamicRuns
{
public int MaximumPeriodInSeconds
{
get { return 30; }
}
public int MinimumPeriodInSeconds
{
get { return 20; }
}
public Task<bool> Run()
{
Trace.TraceInformation("Scalable Task Running.");
return Task.FromResult(true);
}
}
}```
Scale up and down in demo | ```c#
namespace Worker.Scalable
{
using King.Service;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
public class ScalableTask : IDynamicRuns
{
public int MaximumPeriodInSeconds
{
get
{
return 30;
}
}
public int MinimumPeriodInSeconds
{
get
{
return 20;
}
}
public Task<bool> Run()
{
var random = new Random();
var workWasDone = (random.Next() % 2) == 0;
Trace.TraceInformation("Work was done: {0}", workWasDone);
return Task.FromResult(workWasDone);
}
}
}``` |
cda42b87-9362-46d5-9bfc-ad58c5733205 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingShow>, TraktTrendingShow>
{
internal TraktShowsTrendingRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/trending{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
```
Add filter property to trending shows request. | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingShow>, TraktTrendingShow>
{
internal TraktShowsTrendingRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/trending{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktShowFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
``` |
47ec220e-ac73-483c-a108-9ea589672e26 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using LinqToDB;
using NUnit.Framework;
namespace Tests.UserTests
{
[TestFixture]
public class Issue1556Tests : TestBase
{
[Test]
public void Issue1556Test([DataSources(ProviderName.Sybase, ProviderName.OracleNative)] string context)
{
using (var db = GetDataContext(context))
{
AreEqual(
from p in db.Parent
from c in db.Child
where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID)
select new { p, c }
,
db.Parent
.InnerJoin(db.Child,
(p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID),
(p,c) => new { p, c }));
}
}
}
}
```
Access dos not support such join syntax. | ```c#
using System;
using System.Linq;
using LinqToDB;
using NUnit.Framework;
namespace Tests.UserTests
{
[TestFixture]
public class Issue1556Tests : TestBase
{
[Test]
public void Issue1556Test(
[DataSources(ProviderName.Sybase, ProviderName.OracleNative, ProviderName.Access)] string context)
{
using (var db = GetDataContext(context))
{
AreEqual(
from p in db.Parent
from c in db.Child
where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID)
select new { p, c }
,
db.Parent
.InnerJoin(db.Child,
(p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID),
(p,c) => new { p, c }));
}
}
}
}
``` |
5c60f56b-8de8-4bca-8ae7-f064e60a2857 | {
"language": "C#"
} | ```c#
using System.Net.Http;
using System.Threading.Tasks;
using Anemonis.MicrosoftOffice.AddinHost.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace Anemonis.MicrosoftOffice.AddinHost.IntegrationTests
{
[TestClass]
public sealed class RequestTracingMiddlewareTests
{
[TestMethod]
public async Task Trace()
{
var loggerMock = new Mock<Serilog.ILogger>(MockBehavior.Strict);
loggerMock.Setup(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<object[]>()));
var builder = new WebHostBuilder()
.ConfigureServices(sc => sc
.AddSingleton(loggerMock.Object)
.AddSingleton<RequestTracingMiddleware, RequestTracingMiddleware>())
.Configure(ab => ab
.UseMiddleware<RequestTracingMiddleware>());
using (var server = new TestServer(builder))
{
using (var client = server.CreateClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, server.BaseAddress);
var response = await client.SendAsync(request);
}
}
loggerMock.Verify(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<object[]>()), Times.Exactly(1));
}
}
}```
Fix integration tests for tracing | ```c#
using System.Net.Http;
using System.Threading.Tasks;
using Anemonis.MicrosoftOffice.AddinHost.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace Anemonis.MicrosoftOffice.AddinHost.IntegrationTests
{
[TestClass]
public sealed class RequestTracingMiddlewareTests
{
[TestMethod]
public async Task Trace()
{
var loggerMock = new Mock<Serilog.ILogger>(MockBehavior.Strict);
loggerMock.Setup(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>()));
var builder = new WebHostBuilder()
.ConfigureServices(sc => sc
.AddSingleton(loggerMock.Object)
.AddSingleton<RequestTracingMiddleware, RequestTracingMiddleware>())
.Configure(ab => ab
.UseMiddleware<RequestTracingMiddleware>());
using (var server = new TestServer(builder))
{
using (var client = server.CreateClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, server.BaseAddress);
var response = await client.SendAsync(request);
}
}
loggerMock.Verify(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(1));
}
}
}``` |
777e9944-8eea-44c9-9258-ed88e37c2711 | {
"language": "C#"
} | ```c#
using GRA.Domain.Service;
using GRA.Controllers.ViewModel.ParticipatingBranches;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace GRA.Controllers
{
public class ParticipatingBranchesController : Base.UserController
{
private readonly SiteService _siteService;
public static string Name { get { return "ParticipatingBranches"; } }
public ParticipatingBranchesController(ServiceFacade.Controller context,
SiteService siteService)
: base(context)
{
_siteService = siteService ?? throw new ArgumentNullException(nameof(siteService));
}
public async Task<IActionResult> Index()
{
var site = await GetCurrentSiteAsync();
if(await _siteLookupService.GetSiteSettingBoolAsync(site.Id,
SiteSettingKey.Users.ShowLinkToParticipatingBranches))
{
var viewModel = new ParticipatingBranchesViewModel
{
Systems = await _siteService.GetSystemList()
};
return View(nameof(Index), viewModel);
}
else
{
return StatusCode(404);
}
}
}
}
```
Access always to list of branches | ```c#
using GRA.Domain.Service;
using GRA.Controllers.ViewModel.ParticipatingBranches;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace GRA.Controllers
{
public class ParticipatingBranchesController : Base.UserController
{
private readonly SiteService _siteService;
public static string Name { get { return "ParticipatingBranches"; } }
public ParticipatingBranchesController(ServiceFacade.Controller context,
SiteService siteService)
: base(context)
{
_siteService = siteService ?? throw new ArgumentNullException(nameof(siteService));
}
public async Task<IActionResult> Index()
{
var site = await GetCurrentSiteAsync();
var viewModel = new ParticipatingBranchesViewModel
{
Systems = await _siteService.GetSystemList()
};
return View(nameof(Index), viewModel);
}
}
}
``` |
c956dad9-59b7-482f-81c7-5ba49b126f6e | {
"language": "C#"
} | ```c#
using System;
namespace OpenWeatherMap.Standard.Models
{
/// <summary>
/// wind model
/// </summary>
[Serializable]
public class Wind : BaseModel
{
private float speed, gust;
private int deg;
/// <summary>
/// wind speed
/// </summary>
public float Speed
{
get => speed;
set => SetProperty(ref speed, value);
}
/// <summary>
/// wind degree
/// </summary>
public int Degree
{
get => deg;
set => SetProperty(ref deg, value);
}
/// <summary>
/// gust
/// </summary>
public float Gust
{
get => gust;
set => SetProperty(ref gust, value);
}
}
}
```
Fix wind Degree not using the right name for the json file | ```c#
using Newtonsoft.Json;
using System;
namespace OpenWeatherMap.Standard.Models
{
/// <summary>
/// wind model
/// </summary>
[Serializable]
public class Wind : BaseModel
{
private float speed, gust;
private int deg;
/// <summary>
/// wind speed
/// </summary>
public float Speed
{
get => speed;
set => SetProperty(ref speed, value);
}
/// <summary>
/// wind degree
/// </summary>
[JsonProperty("deg")]
public int Degree
{
get => deg;
set => SetProperty(ref deg, value);
}
/// <summary>
/// gust
/// </summary>
public float Gust
{
get => gust;
set => SetProperty(ref gust, value);
}
}
}
``` |
843ca95a-b7f9-4e53-9bcf-d6d8a53a220f | {
"language": "C#"
} | ```c#
using RepoZ.Api.IO;
using System;
using System.Linq;
namespace RepoZ.Api.Mac.IO
{
public class MacDriveEnumerator : IPathProvider
{
public string[] GetPaths()
{
return System.IO.DriveInfo.GetDrives()
.Where(d => d.DriveType == System.IO.DriveType.Fixed)
.Where(p => !p.RootDirectory.FullName.StartsWith("/private", StringComparison.OrdinalIgnoreCase))
.Select(d => d.RootDirectory.FullName)
.ToArray();
}
}
}```
Use the user profile as scan entry point instead of drives like in Windows | ```c#
using RepoZ.Api.IO;
using System;
using System.Linq;
namespace RepoZ.Api.Mac.IO
{
public class MacDriveEnumerator : IPathProvider
{
public string[] GetPaths()
{
return new string[] { Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) };
}
}
}``` |
f51dee6a-4c4f-4a58-a1f8-966d4159c555 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sprache;
using System.Text.RegularExpressions;
using KVLib.KeyValues;
namespace KVLib
{
/// <summary>
/// Parser entry point for reading Key Value strings
/// </summary>
public static class KVParser
{
public static IKVParser KV1 = new KeyValues.SpracheKVParser();
/// <summary>
/// Reads a line of text and returns the first Root key in the text
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
///
[Obsolete("Please use KVParser.KV1.Parse()")]
public static KeyValue ParseKeyValueText(string text)
{
return KV1.Parse(text);
}
/// <summary>
/// Reads a blob of text and returns an array of all root keys in the text
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
///
[Obsolete("Please use KVParser.KV1.ParseAll()")]
public static KeyValue[] ParseAllKVRootNodes(string text)
{
return KV1.ParseAll(text);
}
}
public class KeyValueParsingException : Exception
{
public KeyValueParsingException(string message, Exception inner)
: base(message, inner)
{
}
}
}
```
Set the default parser to the Penguin Parser as it has better error reporting and is faster | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sprache;
using System.Text.RegularExpressions;
using KVLib.KeyValues;
namespace KVLib
{
/// <summary>
/// Parser entry point for reading Key Value strings
/// </summary>
public static class KVParser
{
public static IKVParser KV1 = new KeyValues.PenguinParser();
/// <summary>
/// Reads a line of text and returns the first Root key in the text
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
///
[Obsolete("Please use KVParser.KV1.Parse()")]
public static KeyValue ParseKeyValueText(string text)
{
return KV1.Parse(text);
}
/// <summary>
/// Reads a blob of text and returns an array of all root keys in the text
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
///
[Obsolete("Please use KVParser.KV1.ParseAll()")]
public static KeyValue[] ParseAllKVRootNodes(string text)
{
return KV1.ParseAll(text);
}
}
public class KeyValueParsingException : Exception
{
public KeyValueParsingException(string message, Exception inner)
: base(message, inner)
{
}
}
}
``` |
c145b20d-be54-444e-a2dd-83ff9533ade9 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using HtmlAgilityPack;
namespace ReverseMarkdown.Converters
{
public class Li
: ConverterBase
{
public Li(Converter converter)
: base(converter)
{
this.Converter.Register("li", this);
}
public override string Convert(HtmlNode node)
{
string content = this.TreatChildren(node);
string indentation = IndentationFor(node);
string prefix = PrefixFor(node);
return string.Format("{0}{1}{2}" + Environment.NewLine, indentation, prefix, content.Chomp());
}
private string PrefixFor(HtmlNode node)
{
if (node.ParentNode != null && node.ParentNode.Name == "ol")
{
// index are zero based hence add one
int index = node.ParentNode.SelectNodes("./li").IndexOf(node) + 1;
return string.Format("{0}. ",index);
}
else
{
return "- ";
}
}
private string IndentationFor(HtmlNode node)
{
int length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count();
return new string(' ', Math.Max(length-1,0));
}
}
}
```
Fix nested list item space before to 2 characters GH-14 | ```c#
using System;
using System.Linq;
using HtmlAgilityPack;
namespace ReverseMarkdown.Converters
{
public class Li
: ConverterBase
{
public Li(Converter converter)
: base(converter)
{
this.Converter.Register("li", this);
}
public override string Convert(HtmlNode node)
{
string content = this.TreatChildren(node);
string indentation = IndentationFor(node);
string prefix = PrefixFor(node);
return string.Format("{0}{1}{2}" + Environment.NewLine, indentation, prefix, content.Chomp());
}
private string PrefixFor(HtmlNode node)
{
if (node.ParentNode != null && node.ParentNode.Name == "ol")
{
// index are zero based hence add one
int index = node.ParentNode.SelectNodes("./li").IndexOf(node) + 1;
return string.Format("{0}. ",index);
}
else
{
return "- ";
}
}
private string IndentationFor(HtmlNode node)
{
int length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count();
return new string(' ', Math.Max(length-1,0)*2);
}
}
}
``` |
bce6062d-973b-4c53-a6b7-36f8b482b746 | {
"language": "C#"
} | ```c#
namespace DungeonsAndDragons.DOF
{
public class Character
{
public int Level { get; set; }
public int Strength { get; set; }
public int Dexterity { get; set; }
public IWeapon CurrentWeapon { get; set; }
public int StrengthModifier
{
get { return Strength / 2 - 5; }
}
public int DexterityModifier
{
get { return Dexterity / 2 - 5; }
}
public int BaseMeleeAttack
{
get { return Level / 2 + StrengthModifier; }
}
public int BaseRangedAttack
{
get { return Level / 2 + DexterityModifier; }
}
public int CurrentAttack
{
get
{
if (CurrentWeapon.IsMelee)
return BaseMeleeAttack + CurrentWeapon.AttackBonus;
else
return BaseRangedAttack + CurrentWeapon.AttackBonus;
}
}
public void Equip(IWeapon weapon)
{
CurrentWeapon = weapon;
}
public bool Attack(Creature creature, int roll)
{
return CurrentAttack + roll >= creature.ArmorClass;
}
}
}
```
Use racial attack bonus to compute current attack. | ```c#
namespace DungeonsAndDragons.DOF
{
public class Character
{
public int Level { get; set; }
public int Strength { get; set; }
public int Dexterity { get; set; }
public IWeapon CurrentWeapon { get; set; }
public int StrengthModifier
{
get { return Strength / 2 - 5; }
}
public int DexterityModifier
{
get { return Dexterity / 2 - 5; }
}
public int BaseMeleeAttack
{
get { return Level / 2 + StrengthModifier; }
}
public int BaseRangedAttack
{
get { return Level / 2 + DexterityModifier; }
}
public int GetCurrentAttack(Creature creature)
{
if (CurrentWeapon.IsMelee)
return BaseMeleeAttack + CurrentWeapon.RacialAttackBonus(creature.Race);
else
return BaseRangedAttack + CurrentWeapon.RacialAttackBonus(creature.Race);
}
public void Equip(IWeapon weapon)
{
CurrentWeapon = weapon;
}
public bool Attack(Creature creature, int roll)
{
return GetCurrentAttack(creature) + roll >= creature.ArmorClass;
}
}
}
``` |
e0bc7581-ac34-4dc5-9c6e-27fcf634f45c | {
"language": "C#"
} | ```c#
namespace Stripe.Issuing
{
using Newtonsoft.Json;
public class VerificationData : StripeEntity<VerificationData>
{
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("address_line1_check")]
public string AddressLine1Check { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("address_zip_check")]
public string AddressZipCheck { get; set; }
/// <summary>
/// One of <c>success</c>, <c>failure</c>, <c>exempt</c>, or <c>none</c>.
/// </summary>
[JsonProperty("authentication")]
public string Authentication { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("cvc_check")]
public string CvcCheck { get; set; }
}
}
```
Add support for `ExpiryCheck` on Issuing `Authorization` | ```c#
namespace Stripe.Issuing
{
using Newtonsoft.Json;
public class VerificationData : StripeEntity<VerificationData>
{
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("address_line1_check")]
public string AddressLine1Check { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("address_zip_check")]
public string AddressZipCheck { get; set; }
/// <summary>
/// One of <c>success</c>, <c>failure</c>, <c>exempt</c>, or <c>none</c>.
/// </summary>
[JsonProperty("authentication")]
public string Authentication { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("cvc_check")]
public string CvcCheck { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("expiry_check")]
public string ExpiryCheck { get; set; }
}
}
``` |
28fea31a-a816-4580-a4c7-09fd5071b1c8 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Requests
{
public class Schema
{
public string Url { get; private set; }
public string Base { get; private set; }
public string Path { get; private set; }
public Schema(string url)
{
Url = url.TrimEnd(new char[] { '/' });
var baseAndPath = url.Split('#');
Base = baseAndPath[0];
if (baseAndPath.Length == 2)
{
Path = baseAndPath[1];
}
}
}
}
```
Fix trailing slash in Url | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Requests
{
public class Schema
{
public string Url { get; private set; }
public string Base { get; private set; }
public string Path { get; private set; }
public Schema(string url)
{
Url = url.TrimEnd(new char[] { '/' });
var baseAndPath = Url.Split('#');
Base = baseAndPath[0];
if (baseAndPath.Length == 2)
{
Path = baseAndPath[1];
}
}
}
}
``` |
7838e11b-7cc3-422a-88d2-eada502568a9 | {
"language": "C#"
} | ```c#
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = ClassLibrary1.Class1.ReturnFive();
Console.WriteLine("Hello World!");
}
}
}
```
Add a quick little demo of using a function from the shared class library to ConsoleApp1 | ```c#
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Quick little demo of using a function from the shared class library
int x = ClassLibrary1.Class1.ReturnFive();
System.Diagnostics.Debug.Assert(x == 5);
Console.WriteLine("Hello World!");
}
}
}
``` |
6a9cc342-22bb-4b4f-ad7e-0ffb68249a00 | {
"language": "C#"
} | ```c#
@model IEnumerable<Unit>
<div class="page-header">
<h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var unit in Model)
{
<tr>
<td>@Html.DisplayFor(s => unit)</td>
<td>@Html.DisplayFor(s => unit.UIC)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { unit.Id })
@Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id })
</td>
</tr>
}
</tbody>
</table>
```
Add link to org chart | ```c#
@model IEnumerable<Unit>
<div class="page-header">
<h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var unit in Model)
{
<tr>
<td>@Html.DisplayFor(s => unit)</td>
<td>@Html.DisplayFor(s => unit.UIC)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { unit.Id })
@Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id })
@Html.ActionLink("Org Chart", "Details", new { unit.Id })
</td>
</tr>
}
</tbody>
</table>
``` |
ec357b4e-9a93-4f5f-81d1-63c973ff6837 | {
"language": "C#"
} | ```c#
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Meraki {
public partial class MerakiClient {
private readonly HttpClient _client;
private readonly UrlFormatProvider _formatter = new UrlFormatProvider();
public MerakiClient(IOptions<MerakiClientSettings> options) {
_client = new HttpClient(new HttpClientHandler()) {
BaseAddress = new Uri(options.Value.Address)
};
_client.DefaultRequestHeaders.Add("X-Cisco-Meraki-API-Key", options.Value.Key);
_client.DefaultRequestHeaders.Add("Accept-Type", "application/json");
}
private string Url(FormattableString formattable) => formattable.ToString(_formatter);
public Task<HttpResponseMessage> SendAsync(HttpMethod method, string uri) {
return SendAsync(new HttpRequestMessage(method, uri));
}
internal Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) {
return _client.SendAsync(request);
}
internal async Task<T> GetAsync<T>(string uri) {
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(content);
}
public async Task<string> GetAsync(string uri) {
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var content = await response.Content.ReadAsStringAsync();
return content;
}
}
}```
Allow settings to be passed as well | ```c#
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Meraki {
public partial class MerakiClient {
private readonly HttpClient _client;
private readonly UrlFormatProvider _formatter = new UrlFormatProvider();
public MerakiClient(IOptions<MerakiClientSettings> options)
: this(options.Value) {
}
public MerakiClient(MerakiClientSettings settings) {
_client = new HttpClient(new HttpClientHandler()) {
BaseAddress = new Uri(settings.Address)
};
_client.DefaultRequestHeaders.Add("X-Cisco-Meraki-API-Key", settings.Key);
_client.DefaultRequestHeaders.Add("Accept-Type", "application/json");
}
private string Url(FormattableString formattable) => formattable.ToString(_formatter);
public Task<HttpResponseMessage> SendAsync(HttpMethod method, string uri) => SendAsync(new HttpRequestMessage(method, uri));
internal Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) => _client.SendAsync(request);
internal async Task<T> GetAsync<T>(string uri) {
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(content);
}
public async Task<string> GetAsync(string uri) {
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var content = await response.Content.ReadAsStringAsync();
return content;
}
}
}``` |
26d68c52-a3c1-427a-b056-d32a5bb08634 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScriptGo)]
public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
[DontSerialize]
private PythonExecutionEngine _engine;
protected PythonExecutionEngine Engine
{
get { return _engine; }
}
protected virtual float Delta
{
get { return Time.MsPFMult * Time.TimeMult; }
}
public void OnInit(InitContext context)
{
if (!Script.IsAvailable) return;
_engine = new PythonExecutionEngine(Script.Res.Content);
_engine.SetVariable("gameObject", GameObj);
if (_engine.HasMethod("start"))
_engine.CallMethod("start");
}
public void OnUpdate()
{
if (_engine.HasMethod("update"))
_engine.CallMethod("update", Delta);
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
```
Create exec engine on load and pass context to script | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScriptGo)]
public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
[DontSerialize]
private PythonExecutionEngine _engine;
protected PythonExecutionEngine Engine
{
get { return _engine; }
}
protected virtual float Delta
{
get { return Time.MsPFMult * Time.TimeMult; }
}
public void OnInit(InitContext context)
{
if (!Script.IsAvailable) return;
if (context == InitContext.Loaded)
{
_engine = new PythonExecutionEngine(Script.Res.Content);
_engine.SetVariable("gameObject", GameObj);
}
if (_engine.HasMethod("start"))
_engine.CallMethod("start", context);
}
public void OnUpdate()
{
if (_engine.HasMethod("update"))
_engine.CallMethod("update", Delta);
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
``` |
0b220a82-1c17-4513-ad76-50d6b4ef94a0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace SFA.DAS.EmployerUsers.Api.Controllers
{
[RoutePrefix("api/status")]
public class StatusController : ApiController
{
[Route("")]
public IHttpActionResult Index()
{
// Do some Infrastructre work here to smoke out any issues.
return Ok();
}
}
}
```
Add smoke test to Status controller | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using SFA.DAS.EmployerUsers.Api.Orchestrators;
namespace SFA.DAS.EmployerUsers.Api.Controllers
{
[RoutePrefix("api/status")]
public class StatusController : ApiController
{
private readonly UserOrchestrator _orchestrator;
public StatusController(UserOrchestrator orchestrator)
{
_orchestrator = orchestrator;
}
[Route("")]
public async Task <IHttpActionResult> Index()
{
try
{
// Do some Infrastructre work here to smoke out any issues.
var users = await _orchestrator.UsersIndex(1, 1);
return Ok();
}
catch (Exception e)
{
return InternalServerError(e);
}
}
}
}
``` |
19d80c5c-4306-42b0-81d8-d82c66434582 | {
"language": "C#"
} | ```c#
namespace Siftables
{
public partial class MainWindowView
{
public MainWindowView()
{
InitializeComponent();
}
}
}
```
Break build to test TeamCity. | ```c#
namespace Siftables
{
public partial class MainWindowView
{
public MainWindowView()
{
InitializeComponent();
DoSomething();
}
}
}
``` |
7cc95ad2-9cf7-4acc-b53a-c7a2afa4fbdf | {
"language": "C#"
} | ```c#
namespace Fixie
{
using Internal;
using Internal.Expressions;
/// <summary>
/// Subclass Discovery to customize test discovery rules.
///
/// The default discovery rules are applied to a test assembly whenever the test
/// assembly includes no such subclass.
///
/// By defualt,
///
/// <para>A class is a test class if its name ends with "Tests".</para>
///
/// <para>All public methods in a test class are test methods.</para>
/// </summary>
public class Discovery
{
public Discovery()
{
Config = new Configuration();
Classes = new ClassExpression(Config);
Methods = new MethodExpression(Config);
Parameters = new ParameterSourceExpression(Config);
}
/// <summary>
/// The current state describing the discovery rules. This state can be manipulated through
/// the other properties on Discovery.
/// </summary>
internal Configuration Config { get; }
/// <summary>
/// Defines the set of conditions that describe which classes are test classes.
/// </summary>
public ClassExpression Classes { get; }
/// <summary>
/// Defines the set of conditions that describe which test class methods are test methods,
/// and what order to run them in.
/// </summary>
public MethodExpression Methods { get; }
/// <summary>
/// Defines the set of parameter sources, which provide inputs to parameterized test methods.
/// </summary>
public ParameterSourceExpression Parameters { get; }
}
}```
Fix spelling error in summary comment. | ```c#
namespace Fixie
{
using Internal;
using Internal.Expressions;
/// <summary>
/// Subclass Discovery to customize test discovery rules.
///
/// The default discovery rules are applied to a test assembly whenever the test
/// assembly includes no such subclass.
///
/// By default,
///
/// <para>A class is a test class if its name ends with "Tests".</para>
///
/// <para>All public methods in a test class are test methods.</para>
/// </summary>
public class Discovery
{
public Discovery()
{
Config = new Configuration();
Classes = new ClassExpression(Config);
Methods = new MethodExpression(Config);
Parameters = new ParameterSourceExpression(Config);
}
/// <summary>
/// The current state describing the discovery rules. This state can be manipulated through
/// the other properties on Discovery.
/// </summary>
internal Configuration Config { get; }
/// <summary>
/// Defines the set of conditions that describe which classes are test classes.
/// </summary>
public ClassExpression Classes { get; }
/// <summary>
/// Defines the set of conditions that describe which test class methods are test methods,
/// and what order to run them in.
/// </summary>
public MethodExpression Methods { get; }
/// <summary>
/// Defines the set of parameter sources, which provide inputs to parameterized test methods.
/// </summary>
public ParameterSourceExpression Parameters { get; }
}
}``` |
b6daac99-db64-4036-b966-413a2d999cda | {
"language": "C#"
} | ```c#
using System.Web.UI;
using IntelliFactory.WebSharper;
namespace IntelliFactory.WebSharper.JQuery.Mobile.Resources
{
[IntelliFactory.WebSharper.Core.Attributes.Require(typeof(IntelliFactory.WebSharper.JQuery.Resources.JQuery))]
public class JQueryMobile : IntelliFactory.WebSharper.Core.Resources.BaseResource
{
public JQueryMobile() : base("http://code.jquery.com/mobile/1.2.0-alpha.1",
"/jquery.mobile-1.2.0-alpha.1.min.js",
"/jquery.mobile-1.2.0-alpha.1.min.css") {}
}
}
```
Use stable version of JQueryMobile. | ```c#
using System.Web.UI;
using IntelliFactory.WebSharper;
namespace IntelliFactory.WebSharper.JQuery.Mobile.Resources
{
[IntelliFactory.WebSharper.Core.Attributes.Require(typeof(IntelliFactory.WebSharper.JQuery.Resources.JQuery))]
public class JQueryMobile : IntelliFactory.WebSharper.Core.Resources.BaseResource
{
public JQueryMobile() : base("http://code.jquery.com/mobile/1.1.1",
"/jquery.mobile-1.1.1.min.js",
"/jquery.mobile-1.1.1.min.css") {}
}
}
``` |
0a87b9bc-ae21-4fd2-a4d2-23994df17273 | {
"language": "C#"
} | ```c#
using System;
using Moq;
using Xunit;
namespace MarcinHoppe.LangtonsAnts.Tests
{
public class AntTests
{
[Fact]
public void AntTurnsRightOnWhiteSquare()
{
// Arrange
var ant = AntAt(10, 7);
var board = Mock.Of<Board>(b => b.ColorAt(PositionAt(10, 7)) == Colors.White);
// Act
ant.MoveOn(board);
// Assert
Assert.Equal(PositionAt(10, 8), ant.Position);
}
[Fact]
public void AndTurnsLeftOnBlackSquare()
{
// Arrange
var ant = AntAt(10, 7);
var board = Mock.Of<Board>(b => b.ColorAt(PositionAt(10, 7)) == Colors.Black);
// Act
ant.MoveOn(board);
// Assert
Assert.Equal(PositionAt(10, 6), ant.Position);
}
private Ant AntAt(int row, int column)
{
return new Ant()
{
Position = new Position { Row = row, Column = column }
};
}
private Position PositionAt(int row, int column)
{
return new Position
{
Row = row, Column = column
};
}
}
}
```
Fix typo in unit test name | ```c#
using System;
using Moq;
using Xunit;
namespace MarcinHoppe.LangtonsAnts.Tests
{
public class AntTests
{
[Fact]
public void AntTurnsRightOnWhiteSquare()
{
// Arrange
var ant = AntAt(10, 7);
var board = Mock.Of<Board>(b => b.ColorAt(PositionAt(10, 7)) == Colors.White);
// Act
ant.MoveOn(board);
// Assert
Assert.Equal(PositionAt(10, 8), ant.Position);
}
[Fact]
public void AntTurnsLeftOnBlackSquare()
{
// Arrange
var ant = AntAt(10, 7);
var board = Mock.Of<Board>(b => b.ColorAt(PositionAt(10, 7)) == Colors.Black);
// Act
ant.MoveOn(board);
// Assert
Assert.Equal(PositionAt(10, 6), ant.Position);
}
private Ant AntAt(int row, int column)
{
return new Ant()
{
Position = new Position { Row = row, Column = column }
};
}
private Position PositionAt(int row, int column)
{
return new Position
{
Row = row, Column = column
};
}
}
}
``` |
680d98aa-d10e-4440-866d-6888d399a688 | {
"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("FakeHttpContext.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FakeHttpContext.Tests")]
[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("bdcb2164-56db-4f8c-8e7d-58c36a7408ca")]
// 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")]
```
Disable parallel execution for tests | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
// 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("FakeHttpContext.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FakeHttpContext.Tests")]
[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("bdcb2164-56db-4f8c-8e7d-58c36a7408ca")]
// 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")]
``` |
f8b63df4-279c-44cc-a0e5-1dcffc27b812 | {
"language": "C#"
} | ```c#
#region Usings
using NUnit.Framework;
#endregion
namespace UnitTests
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
Assert.True(true);
}
}
}```
Replace test with test stub | ```c#
#region Usings
using NUnit.Framework;
using WebApplication.Controllers;
#endregion
namespace UnitTests
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var controller = new HabitController();
Assert.True(true);
}
}
}``` |
0f858789-f30d-4226-b67c-bc7841467439 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using Microsoft.WindowsAzure.MobileServices;
namespace MyDriving.AzureClient
{
public class AzureClient : IAzureClient
{
const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
IMobileServiceClient client;
string mobileServiceUrl;
public IMobileServiceClient Client => client ?? (client = CreateClient());
IMobileServiceClient CreateClient()
{
client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
{
SerializerSettings = new MobileServiceJsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
CamelCasePropertyNames = true
}
};
return client;
}
}
}```
Make sure there is only one MobileServiceClient | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using Microsoft.WindowsAzure.MobileServices;
namespace MyDriving.AzureClient
{
public class AzureClient : IAzureClient
{
const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
static IMobileServiceClient client;
public IMobileServiceClient Client => client ?? (client = CreateClient());
IMobileServiceClient CreateClient()
{
client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
{
SerializerSettings = new MobileServiceJsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
CamelCasePropertyNames = true
}
};
return client;
}
}
}``` |
7eacc8fd-296b-4f8c-a567-9a095a6aee45 | {
"language": "C#"
} | ```c#
using Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;
namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts;
[Feature(FeatureIds.SiteTexts)]
public class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<ISiteTextService, SiteTextService>();
}
}
[Feature("OrchardCore.ContentLocalization")]
public class ContentLocalizationStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.RemoveImplementations<ISiteTextService>();
services.AddScoped<ISiteTextService, ContentLocalizationSiteTextService>();
}
}
```
Correct feature attribute to indicate dependency. | ```c#
using Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;
namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts;
[Feature(FeatureIds.SiteTexts)]
public class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<ISiteTextService, SiteTextService>();
}
}
[RequireFeatures("OrchardCore.ContentLocalization")]
public class ContentLocalizationStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.RemoveImplementations<ISiteTextService>();
services.AddScoped<ISiteTextService, ContentLocalizationSiteTextService>();
}
}
``` |
7c04f33d-c86f-4029-86f2-93dec6e6ea6a | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
namespace Clubhouse.io.net.Entities.Labels
{
public class ClubhouseCreateLabelParams
{
[JsonProperty(PropertyName = "color")]
public string Color { get; set; }
[JsonProperty(PropertyName = "external_id")]
public string ExternalID { get; set; }
[JsonProperty(PropertyName = "name", Required = Required.Always)]
public string Name { get; set; }
}
}
```
Create Label failing due to null Color & ExternalID being sent to API | ```c#
using Newtonsoft.Json;
namespace Clubhouse.io.net.Entities.Labels
{
public class ClubhouseCreateLabelParams
{
[JsonProperty(PropertyName = "color", NullValueHandling = NullValueHandling.Ignore)]
public string Color { get; set; }
[JsonProperty(PropertyName = "external_id", NullValueHandling = NullValueHandling.Ignore)]
public string ExternalID { get; set; }
[JsonProperty(PropertyName = "name", Required = Required.Always)]
public string Name { get; set; }
}
}
``` |
1b06f841-247f-4a71-844e-b783d6884f91 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace KotoriCore.Configuration
{
/// <summary>
/// Kotori main configuration.
/// </summary>
public class Kotori
{
/// <summary>
/// Gets or sets the instance.
/// </summary>
/// <value>The instance.</value>
public string Instance { get; set; }
/// <summary>
/// GEts or sets the version of kotori server.
/// </summary>
/// <value>The version.</value>
public string Version { get; set; }
/// <summary>
/// Gets or sets the master keys.
/// </summary>
/// <value>The master keys.</value>
public IEnumerable<MasterKey> MasterKeys { get; set; }
}
}
```
Add DocumentDb connection to main kotori config | ```c#
using System.Collections.Generic;
namespace KotoriCore.Configuration
{
/// <summary>
/// Kotori main configuration.
/// </summary>
public class Kotori
{
/// <summary>
/// Gets or sets the instance.
/// </summary>
/// <value>The instance.</value>
public string Instance { get; set; }
/// <summary>
/// GEts or sets the version of kotori server.
/// </summary>
/// <value>The version.</value>
public string Version { get; set; }
/// <summary>
/// Gets or sets the master keys.
/// </summary>
/// <value>The master keys.</value>
public IEnumerable<MasterKey> MasterKeys { get; set; }
/// <summary>
/// Gets or sets the document db connection string.
/// </summary>
/// <value>The document db.</value>
public DocumentDb DocumentDb { get; set; }
}
}
``` |
ef1f20e8-b295-444c-802a-1f21eccc52cc | {
"language": "C#"
} | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.Tests
{
public partial class MagickNETTests
{
[TestClass]
public class TheDelegatesProperty
{
[TestMethod]
public void ShouldReturnAllDelegates()
{
var delegates = MagickNET.Delegates; // Cannot detect difference between macOS and Linux build at the moment
#if WINDOWS_BUILD
Assert.AreEqual("cairo flif freetype gslib heic jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib", delegates);
#else
Assert.AreEqual("fontconfig freetype heic jng jp2 jpeg lcms openexr png raw tiff webp xml zlib", delegates);
#endif
}
}
}
}```
Change because lqr support was added to the Linux and macOS build. | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.Tests
{
public partial class MagickNETTests
{
[TestClass]
public class TheDelegatesProperty
{
[TestMethod]
public void ShouldReturnAllDelegates()
{
var delegates = MagickNET.Delegates; // Cannot detect difference between macOS and Linux build at the moment
#if WINDOWS_BUILD
Assert.AreEqual("cairo flif freetype gslib heic jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib", delegates);
#else
Assert.AreEqual("fontconfig freetype heic jng jp2 jpeg lcms lqr openexr png raw tiff webp xml zlib", delegates);
#endif
}
}
}
}``` |
81b114e8-c45a-44f6-8f14-14ab59c879ae | {
"language": "C#"
} | ```c#
using System;
using System.Drawing;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
}
}
```
Fix mono bug in the FontHelper class | ```c#
using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[Test]
public void MakeFont_FontName_ValidFont()
{
using (var sourceFont = SystemFonts.DefaultFont)
{
using (var returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name))
{
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
}
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
using (var sourceFont = new Font(family, 10f, FontStyle.Regular))
{
using (var returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold))
{
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
}
}
break;
}
}
}
}
``` |
0954762f-e877-48ef-aa9c-2016b509d45d | {
"language": "C#"
} | ```c#
using CrossStitch.Core.Configuration;
namespace CrossStitch.Core.Modules.Stitches
{
public class StitchesConfiguration : IModuleConfiguration
{
public static StitchesConfiguration GetDefault()
{
return ConfigurationLoader.GetConfiguration<StitchesConfiguration>("stitches.json");
}
public string DataBasePath { get; set; }
public string AppLibraryBasePath { get; set; }
public string RunningAppBasePath { get; set; }
public void ValidateAndSetDefaults()
{
}
}
}```
Add some default values for StitchConfiguration | ```c#
using CrossStitch.Core.Configuration;
namespace CrossStitch.Core.Modules.Stitches
{
public class StitchesConfiguration : IModuleConfiguration
{
public static StitchesConfiguration GetDefault()
{
return ConfigurationLoader.GetConfiguration<StitchesConfiguration>("stitches.json");
}
public string DataBasePath { get; set; }
public string AppLibraryBasePath { get; set; }
public string RunningAppBasePath { get; set; }
public void ValidateAndSetDefaults()
{
if (string.IsNullOrEmpty(DataBasePath))
DataBasePath = ".\\StitchData";
if (string.IsNullOrEmpty(AppLibraryBasePath))
AppLibraryBasePath = ".\\StitchLibrary";
if (string.IsNullOrEmpty(RunningAppBasePath))
RunningAppBasePath = ".\\RunningStitches";
}
}
}``` |
9dba614a-4ebe-4d2f-9c3a-d56d8ac43393 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new TestAudioCollectionManager();
var threadExecutionFinished = new ManualResetEventSlim();
var updateLoopStarted = new ManualResetEventSlim();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++)
manager.AddItem(new TestingAdjustableAudioComponent());
// in a separate thread start processing the queue
var thread = new Thread(() =>
{
while (!manager.IsDisposed)
{
manager.Update();
updateLoopStarted.Set();
}
threadExecutionFinished.Set();
});
thread.Start();
Assert.IsTrue(updateLoopStarted.Wait(1000));
Assert.DoesNotThrow(() => manager.Dispose());
Assert.IsTrue(threadExecutionFinished.Wait(1000));
}
private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
{
public new bool IsDisposed => base.IsDisposed;
}
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
}
}
```
Increase test wait times (appveyor be slow) | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new TestAudioCollectionManager();
var threadExecutionFinished = new ManualResetEventSlim();
var updateLoopStarted = new ManualResetEventSlim();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++)
manager.AddItem(new TestingAdjustableAudioComponent());
// in a separate thread start processing the queue
var thread = new Thread(() =>
{
while (!manager.IsDisposed)
{
manager.Update();
updateLoopStarted.Set();
}
threadExecutionFinished.Set();
});
thread.Start();
Assert.IsTrue(updateLoopStarted.Wait(10000));
Assert.DoesNotThrow(() => manager.Dispose());
Assert.IsTrue(threadExecutionFinished.Wait(10000));
}
private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
{
public new bool IsDisposed => base.IsDisposed;
}
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
}
}
``` |
e58fd792-12f4-431c-8575-b8012d110ec3 | {
"language": "C#"
} | ```c#
using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
}
[Test]
public void OnSecretSplit_FlagsShouldBeTrue()
{
var splitter = new SecretSplittingProvider(Message, RandBytes);
splitter.SplitSecretBetweenTwoPeople();
Assert.IsTrue(splitter.IsRProtected);
Assert.IsTrue(splitter.IsSProtected);
Assert.IsTrue(splitter.IsSecretMessageProtected);
}
}
}
```
Fix unit test so it does unprotecting and padding | ```c#
using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
private const int Padding = 16;
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
Helpers.ToggleMemoryProtection(_splitter);
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
var toPad = Message;
Helpers.PadArrayToMultipleOf(ref toPad, Padding);
Helpers.ToggleMemoryProtection(_splitter);
Assert.AreEqual(Helpers.GetString(toPad), Helpers.GetString(m));
}
[Test]
public void OnSecretSplit_FlagsShouldBeTrue()
{
var splitter = new SecretSplittingProvider(Message, RandBytes);
splitter.SplitSecretBetweenTwoPeople();
Assert.IsTrue(splitter.IsRProtected);
Assert.IsTrue(splitter.IsSProtected);
Assert.IsTrue(splitter.IsSecretMessageProtected);
}
}
}
``` |
14d04fe8-faa6-4dd4-beae-69a62afab71c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using XHRTool.XHRLogic.Common;
namespace XHRTool.UI.WPF.ViewModels
{
[Serializable]
public class UrlHistoryModel
{
public UrlHistoryModel(string url, string verb)
{
Url = url;
Verb = verb;
}
public string Url { get; set; }
public string Verb { get; set; }
}
public class UrlHistoryModelEqualityComparer : IEqualityComparer<UrlHistoryModel>
{
public bool Equals(UrlHistoryModel x, UrlHistoryModel y)
{
return x.Url.Equals(y.Url) && x.Verb.Equals(y.Verb);
}
public int GetHashCode(UrlHistoryModel obj)
{
return (obj.Verb.GetHashCode() + obj.Url.GetHashCode()) / 2;
}
}
}
```
Fix string comparison for URL history | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using XHRTool.XHRLogic.Common;
namespace XHRTool.UI.WPF.ViewModels
{
[Serializable]
public class UrlHistoryModel
{
public UrlHistoryModel(string url, string verb)
{
Url = url;
Verb = verb;
}
public string Url { get; set; }
public string Verb { get; set; }
}
public class UrlHistoryModelEqualityComparer : IEqualityComparer<UrlHistoryModel>
{
public bool Equals(UrlHistoryModel x, UrlHistoryModel y)
{
return x.Url.Equals(y.Url, StringComparison.OrdinalIgnoreCase) && x.Verb.Equals(y.Verb, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(UrlHistoryModel obj)
{
return (obj.Verb.GetHashCode() + obj.Url.GetHashCode()) / 2;
}
}
}
``` |
7a676c27-4a73-41bf-af98-ca85d11ac174 | {
"language": "C#"
} | ```c#
namespace Stripe
{
using Newtonsoft.Json;
public class BillingDetailsOptions : INestedOptions
{
[JsonProperty("address")]
public AddressOptions Address { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("line1")]
public string Line1 { get; set; }
[JsonProperty("line2")]
public string Line2 { get; set; }
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
}
```
Fix BillingDetails on PaymentMethod creation to have the right params | ```c#
namespace Stripe
{
using Newtonsoft.Json;
public class BillingDetailsOptions : INestedOptions
{
[JsonProperty("address")]
public AddressOptions Address { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("phone")]
public string Phone { get; set; }
}
}
``` |
61a905ec-217c-4032-a726-bc36f6c47caf | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneLoadingSpinner : OsuGridTestScene
{
public TestSceneLoadingSpinner()
: base(2, 2)
{
LoadingSpinner loading;
Cell(0).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(1).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.White,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(2).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(3).AddRange(new Drawable[]
{
loading = new LoadingSpinner()
});
Scheduler.AddDelayed(() => loading.ToggleVisibility(), 200, true);
}
}
}
```
Add test for loading spinner with box | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneLoadingSpinner : OsuGridTestScene
{
public TestSceneLoadingSpinner()
: base(2, 2)
{
LoadingSpinner loading;
Cell(0).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(1).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.White,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner(true)
});
loading.Show();
Cell(2).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(3).AddRange(new Drawable[]
{
loading = new LoadingSpinner()
});
Scheduler.AddDelayed(() => loading.ToggleVisibility(), 200, true);
}
}
}
``` |
5484ea86-9df1-4e50-86fc-d19843c524cc | {
"language": "C#"
} | ```c#
using System.Xml;
namespace umbraco.editorControls.imagecropper
{
public class DataTypeData : umbraco.cms.businesslogic.datatype.DefaultData
{
public DataTypeData(umbraco.cms.businesslogic.datatype.BaseDataType DataType) : base(DataType) { }
public override XmlNode ToXMl(XmlDocument data)
{
if (Value.ToString() != "") {
XmlDocument xd = new XmlDocument();
xd.LoadXml(Value.ToString());
return data.ImportNode(xd.DocumentElement, true);
} else {
return base.ToXMl(data);
}
}
}
}```
Fix U4-2711 add Null Check to ToXMl method | ```c#
using System.Xml;
namespace umbraco.editorControls.imagecropper
{
public class DataTypeData : umbraco.cms.businesslogic.datatype.DefaultData
{
public DataTypeData(umbraco.cms.businesslogic.datatype.BaseDataType DataType) : base(DataType) { }
public override XmlNode ToXMl(XmlDocument data)
{
if (Value!=null && Value.ToString() != "") {
XmlDocument xd = new XmlDocument();
xd.LoadXml(Value.ToString());
return data.ImportNode(xd.DocumentElement, true);
} else {
return base.ToXMl(data);
}
}
}
}``` |
9cc5469f-c2cc-4a68-8a75-6446a3fb2132 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using Treehopper;
using Treehopper.Libraries.Displays;
namespace LedShiftRegisterDemo
{
class Program
{
static void Main(string[] args)
{
App().Wait();
}
static async Task App()
{
var board = await ConnectionService.Instance.GetFirstDeviceAsync();
await board.ConnectAsync();
Console.WriteLine("Connected to " + board);
var driver = new LedShiftRegister(board.Spi, board.Pins[5], board.Pwm1);
driver.Brightness = 0.01;
var bar = new BarGraph(driver.Leds);
while (!Console.KeyAvailable)
{
for (int i = 1; i < 10; i++)
{
bar.Value = i / 10.0;
await Task.Delay(50);
}
for (int i = 10; i >= 0; i--)
{
bar.Value = i / 10.0;
await Task.Delay(50);
}
await Task.Delay(100);
}
board.Disconnect();
}
}
}
```
Use two shift registers with two bar graphs and an collection | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using Treehopper;
using Treehopper.Libraries.Displays;
namespace LedShiftRegisterDemo
{
class Program
{
static void Main(string[] args)
{
App().Wait();
}
static async Task App()
{
var board = await ConnectionService.Instance.GetFirstDeviceAsync();
await board.ConnectAsync();
Console.WriteLine("Connected to " + board);
var driver = new LedShiftRegister(board.Spi, board.Pins[9], board.Pwm1, LedShiftRegister.LedChannelCount.SixteenChannel, 0.1);
var driver2 = new LedShiftRegister(driver, LedShiftRegister.LedChannelCount.SixteenChannel);
driver.Brightness = 0.01;
var leds = driver.Leds.Concat(driver2.Leds);
var ledSet1 = leds.Take(8).Concat(leds.Skip(16).Take(8)).ToList();
var ledSet2 = leds.Skip(8).Take(8).Reverse().Concat(leds.Skip(24).Take(8).Reverse()).ToList();
var bar1 = new BarGraph(ledSet1);
var bar2 = new BarGraph(ledSet2);
var collection = new LedDisplayCollection();
collection.Add(bar1);
collection.Add(bar2);
while (!Console.KeyAvailable)
{
for (int i = 1; i < 16; i++)
{
bar1.Value = i / 16.0;
bar2.Value = i / 16.0;
await collection.Flush();
await Task.Delay(10);
}
await Task.Delay(100);
for (int i = 16; i >= 0; i--)
{
bar1.Value = i / 16.0;
bar2.Value = i / 16.0;
await collection.Flush();
await Task.Delay(10);
}
await Task.Delay(100);
}
board.Disconnect();
}
}
}
``` |
bedb4faf-c7fe-437a-9dab-5fb81c9138b5 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
[TestClass]
public class TraktUserListLikeRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsNotAbstract()
{
typeof(TraktUserListLikeRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSealed()
{
typeof(TraktUserListLikeRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSubclassOfATraktNoContentBodylessPostByIdRequest()
{
typeof(TraktUserListLikeRequest).IsSubclassOf(typeof(ATraktNoContentBodylessPostByIdRequest)).Should().BeTrue();
}
}
}
```
Add test for authorization requirement in TraktUserListLikeRequest | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserListLikeRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsNotAbstract()
{
typeof(TraktUserListLikeRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSealed()
{
typeof(TraktUserListLikeRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSubclassOfATraktNoContentBodylessPostByIdRequest()
{
typeof(TraktUserListLikeRequest).IsSubclassOf(typeof(ATraktNoContentBodylessPostByIdRequest)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestHasAuthorizationRequired()
{
var request = new TraktUserListLikeRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
``` |
ddea8057-937a-453b-aba8-1bfa36b95d93 | {
"language": "C#"
} | ```c#
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Common
{
public partial class InterfaceSelectorComboBox : ComboBox
{
public InterfaceSelectorComboBox()
{
InitializeComponent();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface iface in interfaces)
{
UnicastIPAddressInformationCollection addresses = iface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation address in addresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
Items.Add(address.Address.ToString());
}
}
}
}
}
```
Refresh interface list on change | ```c#
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Common
{
public partial class InterfaceSelectorComboBox : ComboBox
{
public InterfaceSelectorComboBox()
{
InitializeComponent();
Initalize();
NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
private void Initalize()
{
if (InvokeRequired)
{
BeginInvoke((MethodInvoker)Initalize);
return;
}
Items.Clear();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface iface in interfaces)
{
UnicastIPAddressInformationCollection addresses = iface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation address in addresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
Items.Add(address.Address.ToString());
}
}
}
private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
Initalize();
}
private void NetworkChange_NetworkAddressChanged(object sender, System.EventArgs e)
{
Initalize();
}
}
}
``` |
c3c430eb-2983-4bbb-887f-eaff544535ea | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MaxMind.MaxMindDb.Test
{
[TestFixture]
public class ThreadingTest
{
[Test]
public void TestParallelFor()
{
var reader = new MaxMindDbReader("..\\..\\TestData\\GeoLite2-City.mmdb", FileAccessMode.MemoryMapped);
var count = 0;
var ipsAndResults = new Dictionary<IPAddress, string>();
var rand = new Random();
while(count < 10000)
{
var ip = new IPAddress(rand.Next(int.MaxValue));
var resp = reader.Find(ip);
if (resp != null)
{
ipsAndResults.Add(ip, resp.ToString());
count++;
}
}
var ips = ipsAndResults.Keys.ToArray();
Parallel.For(0, ips.Length, (i) =>
{
var ipAddress = ips[i];
var result = reader.Find(ipAddress);
var resultString = result.ToString();
var expectedString = ipsAndResults[ipAddress];
if(resultString != expectedString)
throw new Exception(string.Format("Non-matching zip. Expected {0}, found {1}", expectedString, resultString));
});
}
}
}```
Correct error message in thread test | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MaxMind.MaxMindDb.Test
{
[TestFixture]
public class ThreadingTest
{
[Test]
public void TestParallelFor()
{
var reader = new MaxMindDbReader("..\\..\\TestData\\GeoLite2-City.mmdb", FileAccessMode.MemoryMapped);
var count = 0;
var ipsAndResults = new Dictionary<IPAddress, string>();
var rand = new Random();
while(count < 10000)
{
var ip = new IPAddress(rand.Next(int.MaxValue));
var resp = reader.Find(ip);
if (resp != null)
{
ipsAndResults.Add(ip, resp.ToString());
count++;
}
}
var ips = ipsAndResults.Keys.ToArray();
Parallel.For(0, ips.Length, (i) =>
{
var ipAddress = ips[i];
var result = reader.Find(ipAddress);
var resultString = result.ToString();
var expectedString = ipsAndResults[ipAddress];
if(resultString != expectedString)
throw new Exception(string.Format("Non-matching result. Expected {0}, found {1}", expectedString, resultString));
});
}
}
}``` |
4242c52c-44eb-4a35-a2bd-a7cbeb436395 | {
"language": "C#"
} | ```c#
using Xamarin.Forms;
#if __ANDROID__
using NativePoint = Android.Graphics.PointF;
using NativeColor = Android.Graphics.Color;
#elif __IOS__
using NativePoint = CoreGraphics.CGPoint;
#elif NETFX_CORE
using NativePoint = Windows.Foundation.Point;
#endif
#if NETFX_CORE
using NativeColor = Windows.UI.Color;
#endif
namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.Internal
{
internal static class ExtensionMethods
{
internal static NativeColor ToNativeColor(this Color color)
{
#if NETFX_CORE
return NativeColor.FromArgb((byte)color.A, (byte)color.R, (byte)color.G, (byte)color.B);
#elif __ANDROID__
return NativeColor.Argb((int)color.A, (int)color.R, (int)color.G, (int)color.B);
#endif
}
internal static Color ToXamarinFormsColor(this NativeColor color)
{
return Color.FromRgba(color.R, color.G, color.B, color.A);
}
}
}
```
Fix conversion from Xamarin Forms color to native color | ```c#
using Xamarin.Forms;
#if __ANDROID__
using NativePoint = Android.Graphics.PointF;
using NativeColor = Android.Graphics.Color;
#elif __IOS__
using NativePoint = CoreGraphics.CGPoint;
#elif NETFX_CORE
using NativePoint = Windows.Foundation.Point;
#endif
#if NETFX_CORE
using NativeColor = Windows.UI.Color;
#endif
namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.Internal
{
internal static class ExtensionMethods
{
internal static NativeColor ToNativeColor(this Color color)
{
var a = (byte)(255 * color.A);
var r = (byte)(255 * color.R);
var g = (byte)(255 * color.G);
var b = (byte)(255 * color.B);
#if NETFX_CORE
return NativeColor.FromArgb(a, r, g, b);
#elif __ANDROID__
return NativeColor.Argb(a, r, g, b);
#endif
}
internal static Color ToXamarinFormsColor(this NativeColor color)
{
return Color.FromRgba(color.R, color.G, color.B, color.A);
}
}
}
``` |
9ed48d3a-6107-4b34-bdef-d8d16c5bc932 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Represents an email notification sent a user, employee, or administrator
/// </summary>
public class EmailNotification : Notification
{
public static String QueueName { get { return "EmailNotifications"; } }
/// <summary>
/// Who the email notification should be FROM
/// </summary>
public String FromAddress { get; set; }
/// <summary>
/// A list of email addresses to CC
/// </summary>
public ICollection<String> CC { get; set; }
/// <summary>
/// A list of email addresses to BCC
/// </summary>
public ICollection<String> BCC { get; set; }
/// <summary>
/// The subject line of the email
/// </summary>
public String Subject { get; set; }
/// <summary>
/// Any attachments to the email in the form of URLs to download
/// </summary>
public ICollection<Attachment> Attachments { get; set; }
public EmailNotification()
{
this.Recipients = new List<String>();
this.Attachments = new List<Attachment>();
this.CC = new List<String>();
this.BCC = new List<String>();
}
/// <summary>
/// A file may be attached to the email notification by providing a URL to download
/// the file (will be downloaded by the sending process) and a filename
/// </summary>
public class Attachment
{
public String Filename { get; set; }
public String Uri { get; set; }
}
}
}```
Tweak initialization for email notification | ```c#
using System;
using System.Collections.Generic;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Represents an email notification sent a user, employee, or administrator
/// </summary>
public class EmailNotification : Notification
{
public static String QueueName { get { return "EmailNotifications"; } }
/// <summary>
/// Who the email notification should be FROM
/// </summary>
public String FromAddress { get; set; }
/// <summary>
/// A list of email addresses to CC
/// </summary>
public ICollection<String> CC { get; set; } = new List<String>();
/// <summary>
/// A list of email addresses to BCC
/// </summary>
public ICollection<String> BCC { get; set; } = new List<String>();
/// <summary>
/// The subject line of the email
/// </summary>
public String Subject { get; set; }
/// <summary>
/// Any attachments to the email in the form of URLs to download
/// </summary>
public ICollection<Attachment> Attachments { get; set; } = new List<Attachment>();
/// <summary>
/// A file may be attached to the email notification by providing a URL to download
/// the file (will be downloaded by the sending process) and a filename
/// </summary>
public class Attachment
{
public String Filename { get; set; }
public String Uri { get; set; }
}
}
}``` |
f08d485a-07a0-453b-98c4-da78ab1d4926 | {
"language": "C#"
} | ```c#
using Avalonia.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace WalletWasabi.Gui.Converters
{
public class WindowStateAfterSartJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(WindowState);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
// If minimized, then go with Maximized, because at start it shouldn't run with minimized.
var value = reader.Value as string;
if (string.IsNullOrWhiteSpace(value))
{
return WindowState.Maximized;
}
if (value is null)
{
return WindowState.Maximized;
}
string windowStateString = value.Trim();
if (WindowState.Normal.ToString().Equals(windowStateString, StringComparison.OrdinalIgnoreCase)
|| "normal".Equals(windowStateString, StringComparison.OrdinalIgnoreCase)
|| "norm".Equals(windowStateString, StringComparison.OrdinalIgnoreCase))
{
return WindowState.Normal;
}
else
{
return WindowState.Maximized;
}
}
catch
{
return WindowState.Maximized;
}
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((WindowState)value).ToString());
}
}
}
```
Remove duplicae null check, simplified state check | ```c#
using Avalonia.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace WalletWasabi.Gui.Converters
{
public class WindowStateAfterSartJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(WindowState);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
// If minimized, then go with Maximized, because at start it shouldn't run with minimized.
var value = reader.Value as string;
if (string.IsNullOrWhiteSpace(value))
{
return WindowState.Maximized;
}
var windowStateString = value.Trim();
return windowStateString.StartsWith("norm", StringComparison.OrdinalIgnoreCase)
? WindowState.Normal
: WindowState.Maximized;
}
catch
{
return WindowState.Maximized;
}
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((WindowState)value).ToString());
}
}
}
``` |
f83336ab-4a28-4bed-b909-ac3dee66ac71 | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Data;
using SFA.DAS.EmployerFinance.Interfaces;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
private readonly ICurrentDateTime _currentDateTime;
private readonly IEmployerAccountRepository _accountRepository;
public ExpireFundsJob(
IMessageSession messageSession,
ICurrentDateTime currentDateTime,
IEmployerAccountRepository accountRepository)
{
_messageSession = messageSession;
_currentDateTime = currentDateTime;
_accountRepository = accountRepository;
}
public async Task Run(
[TimerTrigger("0 0 0 28 * *")] TimerInfo timer,
ILogger logger)
{
var now = _currentDateTime.Now;
var accounts = await _accountRepository.GetAllAccounts();
var commands = accounts.Select(a => new ExpireAccountFundsCommand { AccountId = a.Id });
var tasks = commands.Select(c =>
{
var sendOptions = new SendOptions();
sendOptions.RequireImmediateDispatch();
sendOptions.SetMessageId($"{nameof(ExpireAccountFundsCommand)}-{now.Year}-{now.Month}-{c.AccountId}");
return _messageSession.Send(c, sendOptions);
});
await Task.WhenAll(tasks);
}
}
}```
Add logging to webjob start and end | ```c#
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Data;
using SFA.DAS.EmployerFinance.Interfaces;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
private readonly ICurrentDateTime _currentDateTime;
private readonly IEmployerAccountRepository _accountRepository;
public ExpireFundsJob(
IMessageSession messageSession,
ICurrentDateTime currentDateTime,
IEmployerAccountRepository accountRepository)
{
_messageSession = messageSession;
_currentDateTime = currentDateTime;
_accountRepository = accountRepository;
}
public async Task Run(
[TimerTrigger("0 0 0 28 * *")] TimerInfo timer,
ILogger logger)
{
logger.LogInformation($"Starting {nameof(ExpireFundsJob)}");
var now = _currentDateTime.Now;
var accounts = await _accountRepository.GetAllAccounts();
var commands = accounts.Select(a => new ExpireAccountFundsCommand { AccountId = a.Id });
var tasks = commands.Select(c =>
{
var sendOptions = new SendOptions();
sendOptions.RequireImmediateDispatch();
sendOptions.SetMessageId($"{nameof(ExpireAccountFundsCommand)}-{now.Year}-{now.Month}-{c.AccountId}");
return _messageSession.Send(c, sendOptions);
});
await Task.WhenAll(tasks);
logger.LogInformation($"{nameof(ExpireFundsJob)} completed.");
}
}
}``` |
5ca8ef15-c46a-4cff-884e-5c77e5b1d3cc | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class FullscreenTest : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
// Run the program while the window is open.
while (Display.CurrentWindow.IsClosed == false &&
Keyboard.Keys[KeyCode.Escape] == false)
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
}
}```
Add text to fullscreen test. | ```c#
using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class FullscreenTest : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
string text = "Press Esc or Tilde to exit." + Environment.NewLine + "Starting Text";
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
Keyboard.KeyDown += new InputEventHandler(Keyboard_KeyDown);
FontSurface font = FontSurface.AgateSans14;
// Run the program while the window is open.
while (Display.CurrentWindow.IsClosed == false &&
Keyboard.Keys[KeyCode.Escape] == false &&
Keyboard.Keys[KeyCode.Tilde] == false)
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
font.DrawText(text);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
void Keyboard_KeyDown(InputEventArgs e)
{
text += e.KeyString;
}
}
}``` |
261100d1-a41f-4689-a63e-ce11bec8d900 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frenetic.TagHandlers;
using Frenetic.TagHandlers.Objects;
using Voxalia.ServerGame.TagSystem.TagObjects;
using Voxalia.ServerGame.ServerMainSystem;
using Voxalia.ServerGame.EntitySystem;
using Voxalia.Shared;
namespace Voxalia.ServerGame.TagSystem.TagBases
{
class PlayerTagBase : TemplateTags
{
Server TheServer;
// <--[tag]
// @Base player[<TextTag>]
// @Group Entities
// @ReturnType PlayerTag
// @Returns the player with the given name.
// -->
public PlayerTagBase(Server tserver)
{
Name = "player";
TheServer = tserver;
}
public override string Handle(TagData data)
{
string pname = data.GetModifier(0).ToLower();
foreach (PlayerEntity player in TheServer.Players)
{
if (player.Name.ToLower() == pname)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
return new TextTag("{NULL}").Handle(data.Shrink());
}
}
}
```
Extend PlayerTags to accept name or entityID | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frenetic.TagHandlers;
using Frenetic.TagHandlers.Objects;
using Voxalia.ServerGame.TagSystem.TagObjects;
using Voxalia.ServerGame.ServerMainSystem;
using Voxalia.ServerGame.EntitySystem;
using Voxalia.Shared;
namespace Voxalia.ServerGame.TagSystem.TagBases
{
class PlayerTagBase : TemplateTags
{
Server TheServer;
// <--[tag]
// @Base player[<TextTag>]
// @Group Entities
// @ReturnType PlayerTag
// @Returns the player with the given name.
// -->
public PlayerTagBase(Server tserver)
{
Name = "player";
TheServer = tserver;
}
public override string Handle(TagData data)
{
string pname = data.GetModifier(0).ToLower();
long pid;
if (long.TryParse(pname, out pid))
{
foreach (PlayerEntity player in TheServer.Players)
{
if (player.EID == pid)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
}
else
{
foreach (PlayerEntity player in TheServer.Players)
{
if (player.Name.ToLower() == pname)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
}
return new TextTag("{NULL}").Handle(data.Shrink());
}
}
}
``` |
8ff789f7-db45-4c91-b388-cd7a049324e7 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
```
Create server side API for single multiple answer question | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
``` |
4a002458-d6f0-4081-995f-004d51ee8e79 | {
"language": "C#"
} | ```c#
// Copyright 2020, Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// TODO: Generate this file!
// This file contains partial classes for all event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))]
public partial class PubsubMessage { }
}
```
Fix PubSub converter attribute in protobuf | ```c#
// Copyright 2020, Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// TODO: Generate this file!
// This file contains partial classes for all event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<MessagePublishedData>))]
public partial class MessagePublishedData { }
}
``` |
890028aa-b264-4146-ba99-9260d4fcc0e9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using PPTail.Entities;
using PPTail.Interfaces;
namespace PPTail
{
public class Program
{
public static void Main(string[] args)
{
(var argsAreValid, var argumentErrrors) = args.ValidateArguments();
if (argsAreValid)
{
var (sourceConnection, targetConnection, templateConnection) = args.ParseArguments();
var settings = (null as ISettings).Create(sourceConnection, targetConnection, templateConnection);
var templates = (null as IEnumerable<Template>).Create(templateConnection);
var container = (null as IServiceCollection).Create(settings, templates);
var serviceProvider = container.BuildServiceProvider();
// TODO: Move data load here -- outside of the build process
//var contentRepos = serviceProvider.GetServices<IContentRepository>();
//var contentRepo = contentRepos.First(); // TODO: Implement properly
var siteBuilder = serviceProvider.GetService<ISiteBuilder>();
var sitePages = siteBuilder.Build();
// TODO: Change this to use the named provider specified in the input args
var outputRepo = serviceProvider.GetService<Interfaces.IOutputRepository>();
outputRepo.Save(sitePages);
}
else
{
// TODO: Display argument errors to user
throw new NotImplementedException();
}
}
}
}
```
Make the system respect the Target ConnectionString Provider designation. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using PPTail.Entities;
using PPTail.Interfaces;
using PPTail.Extensions;
namespace PPTail
{
public class Program
{
const string _connectionStringProviderKey = "Provider";
public static void Main(string[] args)
{
(var argsAreValid, var argumentErrrors) = args.ValidateArguments();
if (argsAreValid)
{
var (sourceConnection, targetConnection, templateConnection) = args.ParseArguments();
var settings = (null as ISettings).Create(sourceConnection, targetConnection, templateConnection);
var templates = (null as IEnumerable<Template>).Create(templateConnection);
var container = (null as IServiceCollection).Create(settings, templates);
var serviceProvider = container.BuildServiceProvider();
// Generate the website pages
var siteBuilder = serviceProvider.GetService<ISiteBuilder>();
var sitePages = siteBuilder.Build();
// Store the resulting output
var outputRepoInstanceName = settings.TargetConnection.GetConnectionStringValue(_connectionStringProviderKey);
var outputRepo = serviceProvider.GetNamedService<IOutputRepository>(outputRepoInstanceName);
outputRepo.Save(sitePages);
}
else
{
// TODO: Display argument errors to user
throw new NotImplementedException();
}
}
}
}
``` |
a7f06f64-1049-4ccb-bf28-165b5a23bdb3 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Wukong.Models;
namespace Wukong.Controllers
{
[Route("oauth")]
public class AuthController : Controller
{
[HttpGet("all")]
public IEnumerable<OAuthMethod> AllSchemes()
{
return
new List<OAuthMethod>{ new OAuthMethod()
{
Scheme = "Microsoft",
DisplayName = "Microsoft",
Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}"
}};
}
[HttpGet("go/{any}")]
public async Task SignIn(string any, string redirectUri = "/")
{
await HttpContext.ChallengeAsync(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties {
RedirectUri = redirectUri,
IsPersistent = true
});
}
[HttpGet("signout")]
public SignOutResult SignOut(string redirectUrl = "/")
{
return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
}```
Make cookie valid for 30 days. | ```c#
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Wukong.Models;
namespace Wukong.Controllers
{
[Route("oauth")]
public class AuthController : Controller
{
[HttpGet("all")]
public IEnumerable<OAuthMethod> AllSchemes()
{
return
new List<OAuthMethod>{ new OAuthMethod()
{
Scheme = "Microsoft",
DisplayName = "Microsoft",
Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}"
}};
}
[HttpGet("go/{any}")]
public async Task SignIn(string any, string redirectUri = "/")
{
await HttpContext.ChallengeAsync(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties {
RedirectUri = redirectUri,
IsPersistent = true,
ExpiresUtc = System.DateTime.UtcNow.AddDays(30)
});
}
[HttpGet("signout")]
public SignOutResult SignOut(string redirectUrl = "/")
{
return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
}``` |
1293eba3-210a-4095-a3cb-ae032ca54573 | {
"language": "C#"
} | ```c#
using System.IO;
using System.Reflection;
using NUnit.Framework;
public class GitHubAssemblyTests
{
[Theory]
public void GitHub_Assembly_Should_Not_Reference_DesignTime_Assembly(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
Assert.That(referencedAssembly.Name, Does.Not.EndWith(".DesignTime"),
"DesignTime assemblies should be embedded not referenced");
}
}
[DatapointSource]
string[] GitHubAssemblies => Directory.GetFiles(AssemblyDirectory, "GitHub.*.dll");
string AssemblyDirectory => Path.GetDirectoryName(GetType().Assembly.Location);
}
```
Check assemblies reference System.Net.Http v4.0 | ```c#
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
public class GitHubAssemblyTests
{
[Theory]
public void GitHub_Assembly_Should_Not_Reference_DesignTime_Assembly(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
Assert.That(referencedAssembly.Name, Does.Not.EndWith(".DesignTime"),
"DesignTime assemblies should be embedded not referenced");
}
}
[Theory]
public void GitHub_Assembly_Should_Not_Reference_System_Net_Http_Above_4_0(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
if (referencedAssembly.Name == "System.Net.Http")
{
Assert.That(referencedAssembly.Version, Is.EqualTo(new Version("4.0.0.0")));
}
}
}
[DatapointSource]
string[] GitHubAssemblies => Directory.GetFiles(AssemblyDirectory, "GitHub.*.dll");
string AssemblyDirectory => Path.GetDirectoryName(GetType().Assembly.Location);
}
``` |
923cbabe-687c-4ba6-b4bc-72602e04527f | {
"language": "C#"
} | ```c#
using System;
using Quartz.Impl.Calendar;
using Xunit;
namespace Quartz.DynamoDB.Tests
{
/// <summary>
/// Tests the DynamoCalendar serialisation for all quartz derived calendar types.
/// </summary>
public class CalendarSerialisationTests
{
[Fact]
[Trait("Category", "Unit")]
public void BaseCalendarDescription()
{
BaseCalendar cal = new BaseCalendar() { Description = "Hi mum" };
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.Equal(sut.Description, deserialised.Description);
}
}
}
```
Add unit test for annual calendar | ```c#
using System;
using Quartz.Impl.Calendar;
using Xunit;
namespace Quartz.DynamoDB.Tests
{
/// <summary>
/// Tests the DynamoCalendar serialisation for all quartz derived calendar types.
/// </summary>
public class CalendarSerialisationTests
{
/// <summary>
/// Tests that the description property of the base calendar type serialises and deserialises correctly.
/// </summary>
/// <returns>The calendar description.</returns>
[Fact]
[Trait("Category", "Unit")]
public void BaseCalendarDescription()
{
BaseCalendar cal = new BaseCalendar() { Description = "Hi mum" };
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.Equal(sut.Description, deserialised.Description);
}
/// <summary>
/// Tests that the excluded days property of the annual calendar serialises and deserialises correctly.
/// </summary>
[Fact]
[Trait("Category", "Unit")]
public void Annual()
{
var importantDate = new DateTime(2015, 04, 02);
AnnualCalendar cal = new AnnualCalendar();
cal.SetDayExcluded(DateTime.Today, true);
cal.SetDayExcluded(importantDate, true);
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.True(((AnnualCalendar)deserialised.Calendar).IsDayExcluded(DateTime.Today));
Assert.True(((AnnualCalendar)deserialised.Calendar).IsDayExcluded(importantDate));
}
}
}
``` |
d803ccca-8f12-4ed1-b201-8f8260d60edc | {
"language": "C#"
} | ```c#
using KitKare.Data.Models;
using KitKare.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper.QueryableExtensions;
using KitKare.Server.ViewModels;
namespace KitKare.Server.Controllers
{
public class ValuesController : ApiController
{
private IRepository<User> users;
public ValuesController(IRepository<User> users)
{
this.users = users;
}
// GET api/values
public IEnumerable<string> Get()
{
var user = this.users.All().ProjectTo<ProfileViewModel>().FirstOrDefault();
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
```
Debug try catch added to values controller | ```c#
using KitKare.Data.Models;
using KitKare.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper.QueryableExtensions;
using KitKare.Server.ViewModels;
namespace KitKare.Server.Controllers
{
public class ValuesController : ApiController
{
private IRepository<User> users;
public ValuesController(IRepository<User> users)
{
this.users = users;
}
// GET api/values
public IEnumerable<string> Get()
{
try
{
var user = this.users.All().ProjectTo<ProfileViewModel>().FirstOrDefault();
return new string[] { "value1", "value2" };
}
catch (Exception e)
{
return new string[] { e.Message };
}
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
``` |
a41fa099-de4c-4834-a41a-6e99538f2790 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ILCompiler.DependencyAnalysisFramework
{
public interface IDependencyNode
{
bool Marked
{
get;
}
}
public interface IDependencyNode<DependencyContextType> : IDependencyNode
{
bool InterestingForDynamicDependencyAnalysis
{
get;
}
bool HasDynamicDependencies
{
get;
}
bool HasConditionalStaticDependencies
{
get;
}
bool StaticDependenciesAreComputed
{
get;
}
IEnumerable<DependencyNodeCore<DependencyContextType>.DependencyListEntry> GetStaticDependencies(DependencyContextType context);
IEnumerable<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> GetConditionalStaticDependencies(DependencyContextType context);
IEnumerable<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<DependencyContextType>> markedNodes, int firstNode, DependencyContextType context);
}
}
```
Add copyright header to new file | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace ILCompiler.DependencyAnalysisFramework
{
public interface IDependencyNode
{
bool Marked
{
get;
}
}
public interface IDependencyNode<DependencyContextType> : IDependencyNode
{
bool InterestingForDynamicDependencyAnalysis
{
get;
}
bool HasDynamicDependencies
{
get;
}
bool HasConditionalStaticDependencies
{
get;
}
bool StaticDependenciesAreComputed
{
get;
}
IEnumerable<DependencyNodeCore<DependencyContextType>.DependencyListEntry> GetStaticDependencies(DependencyContextType context);
IEnumerable<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> GetConditionalStaticDependencies(DependencyContextType context);
IEnumerable<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<DependencyContextType>> markedNodes, int firstNode, DependencyContextType context);
}
}
``` |
eb884077-a555-4943-b4e2-df7436198802 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Casper {
public class MSBuild : TaskBase {
public string WorkingDirectory { get; set; }
public string ProjectFile { get; set; }
public string[] Targets { get; set; }
public IDictionary<string, string> Properties { get; set; }
public override void Execute() {
List<string> args = new List<string>();
if (null != ProjectFile) {
args.Add(ProjectFile);
}
if (null != Targets) {
args.Add("/t:" + string.Join(";", Targets));
}
if (null != Properties) {
foreach (var entry in Properties) {
args.Add("/p:" + entry.Key + "=" + entry.Value);
}
}
var exec = new Exec {
WorkingDirectory = WorkingDirectory,
Executable = "xbuild",
Arguments = string.Join(" ", args),
};
exec.Execute();
}
}
}
```
Change property types to better match up with Boo syntax | ```c#
using System.Collections.Generic;
using System.Collections;
namespace Casper {
public class MSBuild : TaskBase {
public string WorkingDirectory { get; set; }
public string ProjectFile { get; set; }
public IList Targets { get; set; }
public IDictionary Properties { get; set; }
public override void Execute() {
List<string> args = new List<string>();
if (null != ProjectFile) {
args.Add(ProjectFile);
}
if (null != Targets) {
args.Add("/t:" + string.Join(";", Targets));
}
if (null != Properties) {
foreach (var propertyName in Properties.Keys) {
args.Add("/p:" + propertyName + "=" + Properties[propertyName]);
}
}
var exec = new Exec {
WorkingDirectory = WorkingDirectory,
Executable = "xbuild",
Arguments = string.Join(" ", args),
};
exec.Execute();
}
}
}
``` |
f3d8da8c-dafa-4613-a60b-83199818113a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
yield return typeof(VGACompilerCrash.Kernel);
////yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
//yield return typeof(SimpleStructsAndArraysTest.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
////yield return typeof(FrotzKernel.Kernel);
}
}
}
```
Enable all kernels except FAT. | ```c#
using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
yield return typeof(VGACompilerCrash.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
yield return typeof(SimpleStructsAndArraysTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
//yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
//yield return typeof(FrotzKernel.Kernel);
}
}
}
``` |
b8be9c02-d6bb-4f59-9bf0-c868f7b8033b | {
"language": "C#"
} | ```c#
using System;
using BudgetAnalyser.Engine.BankAccount;
using BudgetAnalyser.Engine.Budget;
using JetBrains.Annotations;
namespace BudgetAnalyser.Engine.Statement.Data
{
[AutoRegisterWithIoC]
internal partial class Mapper_TransactionDto_Transaction
{
private readonly IAccountTypeRepository accountRepo;
private readonly IBudgetBucketRepository bucketRepo;
private readonly ITransactionTypeRepository transactionTypeRepo;
public Mapper_TransactionDto_Transaction([NotNull] IAccountTypeRepository accountRepo, [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] ITransactionTypeRepository transactionTypeRepo)
{
if (accountRepo == null) throw new ArgumentNullException(nameof(accountRepo));
if (bucketRepo == null) throw new ArgumentNullException(nameof(bucketRepo));
if (transactionTypeRepo == null) throw new ArgumentNullException(nameof(transactionTypeRepo));
this.accountRepo = accountRepo;
this.bucketRepo = bucketRepo;
this.transactionTypeRepo = transactionTypeRepo;
}
partial void ToDtoPostprocessing(ref TransactionDto dto, Transaction model)
{
dto.Account = model.Account.Name;
dto.BudgetBucketCode = model.BudgetBucket.Code;
dto.TransactionType = model.TransactionType.Name;
}
partial void ToModelPostprocessing(TransactionDto dto, ref Transaction model)
{
// TODO do these need to be added to the repo here?
model.Account = this.accountRepo.GetByKey(dto.Account);
model.BudgetBucket = this.bucketRepo.GetByCode(dto.BudgetBucketCode);
model.TransactionType = this.transactionTypeRepo.GetOrCreateNew(dto.TransactionType);
}
}
}```
Fix bug in Statement DTO mapper that expected bucket code to always have a value - it can be null. | ```c#
using System;
using BudgetAnalyser.Engine.BankAccount;
using BudgetAnalyser.Engine.Budget;
using JetBrains.Annotations;
namespace BudgetAnalyser.Engine.Statement.Data
{
[AutoRegisterWithIoC]
internal partial class Mapper_TransactionDto_Transaction
{
private readonly IAccountTypeRepository accountRepo;
private readonly IBudgetBucketRepository bucketRepo;
private readonly ITransactionTypeRepository transactionTypeRepo;
public Mapper_TransactionDto_Transaction([NotNull] IAccountTypeRepository accountRepo, [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] ITransactionTypeRepository transactionTypeRepo)
{
if (accountRepo == null) throw new ArgumentNullException(nameof(accountRepo));
if (bucketRepo == null) throw new ArgumentNullException(nameof(bucketRepo));
if (transactionTypeRepo == null) throw new ArgumentNullException(nameof(transactionTypeRepo));
this.accountRepo = accountRepo;
this.bucketRepo = bucketRepo;
this.transactionTypeRepo = transactionTypeRepo;
}
partial void ToDtoPostprocessing(ref TransactionDto dto, Transaction model)
{
dto.Account = model.Account.Name;
dto.BudgetBucketCode = model.BudgetBucket?.Code;
dto.TransactionType = model.TransactionType.Name;
}
partial void ToModelPostprocessing(TransactionDto dto, ref Transaction model)
{
// TODO do these need to be added to the repo here?
model.Account = this.accountRepo.GetByKey(dto.Account);
model.BudgetBucket = this.bucketRepo.GetByCode(dto.BudgetBucketCode);
model.TransactionType = this.transactionTypeRepo.GetOrCreateNew(dto.TransactionType);
}
}
}``` |
56de6788-e125-417f-84ba-6b31fe65c65e | {
"language": "C#"
} | ```c#
namespace Vlc.DotNet.Core
{
public interface IAudioManagement
{
IAudioOutputsManagement Outputs { get; }
}
}
```
Add Audio properties to IAudiomanagement | ```c#
namespace Vlc.DotNet.Core
{
public interface IAudioManagement
{
IAudioOutputsManagement Outputs { get; }
bool IsMute { get; set; }
void ToggleMute();
int Volume { get; set; }
ITracksManagement Tracks { get; }
int Channel { get; set; }
long Delay { get; set; }
}
}
``` |
87ad8b29-b044-4a9a-a3d0-33c7da7eee80 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace JetBrains.ReSharper.Plugins.PresentationAssistant
{
public static class ActionIdBlacklist
{
private static readonly HashSet<string> ActionIds = new HashSet<string>
{
// These are the only actions that should be hidden
"TextControl.Backspace",
"TextControl.Delete",
"TextControl.Cut",
"TextControl.Paste",
"TextControl.Copy",
// Used when code completion window is visible
"TextControl.Up", "TextControl.Down",
"TextControl.PageUp", "TextControl.PageDown",
// If camel humps are enabled in the editor
"TextControl.PreviousWord",
"TextControl.PreviousWord.Selection",
"TextControl.NextWord",
"TextControl.NextWord.Selection",
// VS commands, not R# commands
"Edit.Up", "Edit.Down", "Edit.Left", "Edit.Right", "Edit.PageUp", "Edit.PageDown",
// Make sure we don't try to show the presentation assistant popup just as we're
// killing the popups
PresentationAssistantAction.ActionId
};
public static bool IsBlacklisted(string actionId)
{
return ActionIds.Contains(actionId);
}
}
}```
Improve text control black list | ```c#
using System.Collections.Generic;
namespace JetBrains.ReSharper.Plugins.PresentationAssistant
{
public static class ActionIdBlacklist
{
private static readonly HashSet<string> ActionIds = new HashSet<string>
{
// These are the only actions that should be hidden
"TextControl.Backspace",
"TextControl.Delete",
"TextControl.Cut",
"TextControl.Paste",
"TextControl.Copy",
"TextControl.Left", "TextControl.Right",
"TextControl.Left.Selection", "TextControl.Right.Selection",
"TextControl.Up", "TextControl.Down",
"TextControl.Up.Selection", "TextControl.Down.Selection",
"TextControl.Home", "TextControl.End",
"TextControl.Home.Selection", "TextControl.End.Selection",
"TextControl.PageUp", "TextControl.PageDown",
"TextControl.PageUp.Selection", "TextControl.PageDown.Selection",
"TextControl.PreviousWord", "TextControl.NextWord",
"TextControl.PreviousWord.Selection", "TextControl.NextWord.Selection",
// VS commands, not R# commands
"Edit.Up", "Edit.Down", "Edit.Left", "Edit.Right", "Edit.PageUp", "Edit.PageDown",
// Make sure we don't try to show the presentation assistant popup just as we're
// killing the popups
PresentationAssistantAction.ActionId
};
public static bool IsBlacklisted(string actionId)
{
return ActionIds.Contains(actionId);
}
}
}``` |
840757dd-0fc3-4006-aedb-db366a02ae25 | {
"language": "C#"
} | ```c#
using System.Runtime.Serialization;
namespace Nest
{
public enum StringFielddataFormat
{
[EnumMember(Value = "paged_bytes")]
PagedBytes,
[EnumMember(Value = "doc_values")]
DocValues,
[EnumMember(Value = "disabled")]
Disabled
}
}
```
Remove doc_values fielddata format for strings | ```c#
using System.Runtime.Serialization;
namespace Nest
{
public enum StringFielddataFormat
{
[EnumMember(Value = "paged_bytes")]
PagedBytes,
[EnumMember(Value = "disabled")]
Disabled
}
}
``` |
288297bd-8cca-407a-aafa-7d7aebba48d0 | {
"language": "C#"
} | ```c#
using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
if (birthDay < DateTime.Now)
{
if (birthDay.Year < DateTime.Now.Year)
{
return GetSpan(new DateTime(DateTime.Now.Year, birthDay.Month, birthDay.Day));
}
else
{
return GetSpan(new DateTime(DateTime.Now.Year + 1, birthDay.Month, birthDay.Day));
}
}
var span = birthDay - DateTime.Now;
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
}```
Simplify the code that ensures a birthday is in the future. | ```c#
using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
var span = birthDay - DateTime.Now;
if (span.Days < 0)
{
// If the supplied birthday has already happened, then find the next one that will occur.
int years = span.Days / -365;
span = span.Add(TimeSpan.FromDays((years + 1) * 365));
}
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
}``` |
7ccc4498-26a1-461c-b302-98e6cfff508b | {
"language": "C#"
} | ```c#
using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Builder
{
public class Options
{
[Option('a', "buildDir", Required = true, HelpText = "")]
public string BuildDir { get; set; }
[Option('b', "buildArtifactsCacheDir", Required = false, HelpText = "")]
public string BuildArtifactsCacheDir { get; set; }
[Option('o', "buildpackOrder", Required = false, HelpText = "")]
public string BuildpackOrder { get; set; }
[Option('e', "buildpacksDir", Required = false, HelpText = "")]
public string BuildpacksDir { get; set; }
[Option('c', "outputBuildArtifactsCache", Required = false, HelpText = "")]
public string OutputBuildArtifactsCache { get; set; }
[Option('d', "outputDroplet", Required = true, HelpText = "")]
public string OutputDroplet { get; set; }
[Option('m', "outputMetadata", Required = true, HelpText = "")]
public string OutputMetadata { get; set; }
[Option('s', "skipCertVerify", Required = false, HelpText = "")]
public string SkipCertVerify { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
```
Add new command option "skipDetect" | ```c#
using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Builder
{
public class Options
{
[Option('a', "buildDir", Required = true, HelpText = "")]
public string BuildDir { get; set; }
[Option('b', "buildArtifactsCacheDir", Required = false, HelpText = "")]
public string BuildArtifactsCacheDir { get; set; }
[Option('o', "buildpackOrder", Required = false, HelpText = "")]
public string BuildpackOrder { get; set; }
[Option('e', "buildpacksDir", Required = false, HelpText = "")]
public string BuildpacksDir { get; set; }
[Option('c', "outputBuildArtifactsCache", Required = false, HelpText = "")]
public string OutputBuildArtifactsCache { get; set; }
[Option('d', "outputDroplet", Required = true, HelpText = "")]
public string OutputDroplet { get; set; }
[Option('m', "outputMetadata", Required = true, HelpText = "")]
public string OutputMetadata { get; set; }
[Option('s', "skipCertVerify", Required = false, HelpText = "")]
public string SkipCertVerify { get; set; }
[Option('k', "skipDetect", Required = false, HelpText = "")]
public string skipDetect { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
``` |
15518ed4-a99b-47e1-96fe-7eb4f590e490 | {
"language": "C#"
} | ```c#
using LogicalShift.Reason.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LogicalShift.Reason.Solvers
{
/// <summary>
/// Represents a solver that can solve a single clause
/// </summary>
public class SimpleSingleClauseSolver : ISolver
{
/// <summary>
/// The clause that this will solve
/// </summary>
private readonly IClause _clause;
/// <summary>
/// The solver that will be used for subclauses
/// </summary>
private readonly ISolver _subclauseSolver;
public SimpleSingleClauseSolver(IClause clause, ISolver subclauseSolver)
{
if (clause == null) throw new ArgumentNullException("clause");
if (subclauseSolver == null) throw new ArgumentNullException("subclauseSolver");
_clause = clause;
_subclauseSolver = subclauseSolver;
}
public Task<IQueryResult> Solve(IEnumerable<ILiteral> goals)
{
throw new NotImplementedException();
}
public Func<bool> Call(ILiteral predicate, params IReferenceLiteral[] arguments)
{
throw new NotImplementedException();
}
}
}
```
Add a method to get the assignments from a particular literal when it's used as a predicate | ```c#
using LogicalShift.Reason.Api;
using LogicalShift.Reason.Assignment;
using LogicalShift.Reason.Literals;
using LogicalShift.Reason.Unification;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LogicalShift.Reason.Solvers
{
/// <summary>
/// Represents a solver that can solve a single clause
/// </summary>
public class SimpleSingleClauseSolver : ISolver
{
/// <summary>
/// The clause that this will solve
/// </summary>
private readonly IClause _clause;
/// <summary>
/// The solver that will be used for subclauses
/// </summary>
private readonly ISolver _subclauseSolver;
public SimpleSingleClauseSolver(IClause clause, ISolver subclauseSolver)
{
if (clause == null) throw new ArgumentNullException("clause");
if (subclauseSolver == null) throw new ArgumentNullException("subclauseSolver");
_clause = clause;
_subclauseSolver = subclauseSolver;
}
/// <summary>
/// Retrieves an object representing the assignments for a particular literal when used as a predicate
/// </summary>
private PredicateAssignmentList GetAssignmentsFromPredicate(ILiteral predicate)
{
var result = new PredicateAssignmentList();
if (predicate.UnificationKey != null)
{
foreach (var argument in predicate.Dependencies)
{
result.AddArgument(argument);
}
}
return result;
}
public Task<IQueryResult> Solve(IEnumerable<ILiteral> goals)
{
throw new NotImplementedException();
}
public Func<bool> Call(ILiteral predicate, params IReferenceLiteral[] arguments)
{
throw new NotImplementedException();
}
}
}
``` |
b04380be-49bf-452b-a74e-c2a922ca65b7 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using Realms;
using Realms.Schema;
#nullable enable
namespace osu.Game.Database
{
public class EmptyRealmSet<T> : IRealmCollection<T>
{
private static List<T> emptySet => new List<T>();
public IEnumerator<T> GetEnumerator()
{
return emptySet.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)emptySet).GetEnumerator();
}
public int Count => emptySet.Count;
public T this[int index] => emptySet[index];
public event NotifyCollectionChangedEventHandler? CollectionChanged
{
add => throw new NotImplementedException();
remove => throw new NotImplementedException();
}
public event PropertyChangedEventHandler? PropertyChanged
{
add => throw new NotImplementedException();
remove => throw new NotImplementedException();
}
public int IndexOf(object item)
{
return emptySet.IndexOf((T)item);
}
public bool Contains(object item)
{
return emptySet.Contains((T)item);
}
public IRealmCollection<T> Freeze()
{
throw new NotImplementedException();
}
public IDisposable SubscribeForNotifications(NotificationCallbackDelegate<T> callback)
{
throw new NotImplementedException();
}
public bool IsValid => throw new NotImplementedException();
public Realm Realm => throw new NotImplementedException();
public ObjectSchema ObjectSchema => throw new NotImplementedException();
public bool IsFrozen => throw new NotImplementedException();
}
}
```
Use `Array.Empty` instead of constructed list | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using Realms;
using Realms.Schema;
#nullable enable
namespace osu.Game.Database
{
public class EmptyRealmSet<T> : IRealmCollection<T>
{
private IList<T> emptySet => Array.Empty<T>();
public IEnumerator<T> GetEnumerator() => emptySet.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => emptySet.GetEnumerator();
public int Count => emptySet.Count;
public T this[int index] => emptySet[index];
public int IndexOf(object item) => emptySet.IndexOf((T)item);
public bool Contains(object item) => emptySet.Contains((T)item);
public event NotifyCollectionChangedEventHandler? CollectionChanged
{
add => throw new NotImplementedException();
remove => throw new NotImplementedException();
}
public event PropertyChangedEventHandler? PropertyChanged
{
add => throw new NotImplementedException();
remove => throw new NotImplementedException();
}
public IRealmCollection<T> Freeze() => throw new NotImplementedException();
public IDisposable SubscribeForNotifications(NotificationCallbackDelegate<T> callback) => throw new NotImplementedException();
public bool IsValid => throw new NotImplementedException();
public Realm Realm => throw new NotImplementedException();
public ObjectSchema ObjectSchema => throw new NotImplementedException();
public bool IsFrozen => throw new NotImplementedException();
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.