doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
9cec52d7-0e51-4bd8-9818-6dc674a9046c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FuzzyCore.Server;
namespace FuzzyCore.Commands
{
public class GetFile
{
ConsoleMessage Message = new ConsoleMessage();
public void GetFileBytes(Data.JsonCommand Command)
{
try
{
byte[] file = File.ReadAllBytes(Command.FilePath + "\\" + Command.Text);
if (file.Length > 0)
{
SendDataArray(file, Command.Client_Socket);
Message.Write(Command.CommandType,ConsoleMessage.MessageType.SUCCESS);
}
}
catch (Exception ex)
{
Message.Write(ex.Message, ConsoleMessage.MessageType.ERROR);
}
}
public void SendDataArray(byte[] Data, Socket Client)
{
try
{
Thread.Sleep(100);
Client.Send(Data);
}
catch (Exception ex)
{
Message.Write(ex.Message, ConsoleMessage.MessageType.ERROR);
}
}
}
}
```
Delete sender and edit constructor functions | ```c#
using FuzzyCore.Data;
using FuzzyCore.Server;
using System;
using System.IO;
namespace FuzzyCore.Commands
{
public class GetFile
{
ConsoleMessage Message = new ConsoleMessage();
private String FilePath;
private String FileName;
private JsonCommand mCommand;
public GetFile(Data.JsonCommand Command)
{
FilePath = Command.FilePath;
FileName = Command.Text;
this.mCommand = Command;
}
bool FileControl()
{
FileInfo mfileInfo = new FileInfo(FilePath);
return mfileInfo.Exists;
}
public byte[] GetFileBytes()
{
if (FileControl())
{
byte[] file = File.ReadAllBytes(FilePath + "/" + FileName);
return file;
}
return new byte[0];
}
public string GetFileText()
{
if (FileControl())
{
return File.ReadAllText(FilePath + "/" + FileName);
}
return "";
}
}
}
``` |
e6e33181-350b-4dd8-9937-d5cb92de95a4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace EchoClient
{
class Program
{
static void Main(string[] args)
{
Task main = MainAsync(args);
main.Wait();
}
static async Task MainAsync(string[] args)
{
TcpClient client = new TcpClient("::1", 8080);
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };
while (true)
{
Console.WriteLine("What to send?");
string line = Console.ReadLine();
await writer.WriteLineAsync(line);
string response = await reader.ReadLineAsync();
Console.WriteLine($"Response from server {response}");
}
client.Close();
}
}
}
```
Add write retry mechanism into the client. | ```c#
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace EchoClient
{
class Program
{
const int MAX_WRITE_RETRY = 3;
const int WRITE_RETRY_DELAY_SECONDS = 3;
static void Main(string[] args)
{
Task main = MainAsync(args);
main.Wait();
}
static async Task MainAsync(string[] args)
{
using (TcpClient client = new TcpClient("::1", 8080))
{
using (NetworkStream stream = client.GetStream())
{
using (StreamReader reader = new StreamReader(stream))
{
using (StreamWriter writer = new StreamWriter(stream) { AutoFlush = true })
{
while (true)
{
Console.WriteLine("What to send?");
string line = Console.ReadLine();
int writeTry = 0;
bool writtenSuccessfully = false;
while (!writtenSuccessfully && writeTry < MAX_WRITE_RETRY)
{
try
{
writeTry++;
await writer.WriteLineAsync(line);
writtenSuccessfully = true;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to send data to server, try {writeTry} / {MAX_WRITE_RETRY}");
if (!writtenSuccessfully && writeTry == MAX_WRITE_RETRY)
{
Console.WriteLine($"Write retry reach, please check your connectivity with the server and try again. Error details: {Environment.NewLine}{ex.Message}");
}
else
{
await Task.Delay(WRITE_RETRY_DELAY_SECONDS * 1000);
}
}
}
if (!writtenSuccessfully)
{
continue;
}
string response = await reader.ReadLineAsync();
Console.WriteLine($"Response from server {response}");
}
}
}
}
}
}
}
}
``` |
17d90b96-0888-484e-a2d4-9a401c23e1b8 | {
"language": "C#"
} | ```c#
using Alensia.Core.Input.Generic;
using UnityEngine.Assertions;
namespace Alensia.Core.Input
{
public class BindingKey<T> : IBindingKey<T> where T : IInput
{
public string Id { get; }
public BindingKey(string id)
{
Assert.IsNotNull(id, "id != null");
Id = id;
}
public override bool Equals(object obj)
{
var item = obj as BindingKey<T>;
return item != null && Id.Equals(item.Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
}```
Use expression bodied methods for compact code | ```c#
using Alensia.Core.Input.Generic;
using UnityEngine.Assertions;
namespace Alensia.Core.Input
{
public class BindingKey<T> : IBindingKey<T> where T : IInput
{
public string Id { get; }
public BindingKey(string id)
{
Assert.IsNotNull(id, "id != null");
Id = id;
}
public override bool Equals(object obj) => Id.Equals((obj as BindingKey<T>)?.Id);
public override int GetHashCode() => Id.GetHashCode();
}
}``` |
288ee583-9296-49c0-8619-c9861110e181 | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.ModelConventions;
namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels
{
public static class TestModel
{
public static IModel Model
{
get
{
var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet());
builder.Entity<Product>()
.Reference(p => p.ProductCategory)
.InverseCollection(c => c.CategoryProducts)
.ForeignKey(e => e.ProductCategoryId);
return builder.Model;
}
}
}
}```
Fix build: react to EF namespace change | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.Conventions.Internal;
namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels
{
public static class TestModel
{
public static IModel Model
{
get
{
var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet());
builder.Entity<Product>()
.Reference(p => p.ProductCategory)
.InverseCollection(c => c.CategoryProducts)
.ForeignKey(e => e.ProductCategoryId);
return builder.Model;
}
}
}
}``` |
e953e7a2-0315-4a06-bbbc-420a16a13246 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AudioSharp")]
[assembly: AssemblyCopyright("Copyright (c) 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.3.0")]
[assembly: AssemblyFileVersion("1.4.3.0")]
```
Update copyright year in assembly info | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AudioSharp")]
[assembly: AssemblyCopyright("Copyright (c) 2015-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.3.0")]
[assembly: AssemblyFileVersion("1.4.3.0")]
``` |
9d744969-04ad-494d-8e1b-4df8a9d7adb6 | {
"language": "C#"
} | ```c#
using System.Text;
using DotNetRu.Utils.Helpers;
using Newtonsoft.Json;
namespace DotNetRu.Clients.UI
{
public class AppConfig
{
public string AppCenterAndroidKey { get; set; }
public string AppCenteriOSKey { get; set; }
public string PushNotificationsChannel { get; set; }
public string UpdateFunctionURL { get; set; }
public string TweetFunctionUrl { get; set; }
public static AppConfig GetConfig()
{
#if DEBUG
return new AppConfig()
{
AppCenterAndroidKey = "6f9a7703-8ca4-477e-9558-7e095f7d20aa",
AppCenteriOSKey = "1e7f311f-1055-4ec9-8b00-0302015ab8ae",
PushNotificationsChannel = "AuditUpdateDebug",
UpdateFunctionURL = "https://dotnetruapp.azurewebsites.net/api/Update",
TweetFunctionUrl = "https://dotnettweetservice.azurewebsites.net/api/Tweets"
};
#endif
#pragma warning disable CS0162 // Unreachable code detected
var configBytes = ResourceHelper.ExtractResource("DotNetRu.Utils.Config.config.json");
var configBytesAsString = Encoding.UTF8.GetString(configBytes);
return JsonConvert.DeserializeObject<AppConfig>(configBytesAsString);
#pragma warning restore CS0162 // Unreachable code detected
}
}
}
```
Update link to Update function | ```c#
using System.Text;
using DotNetRu.Utils.Helpers;
using Newtonsoft.Json;
namespace DotNetRu.Clients.UI
{
public class AppConfig
{
public string AppCenterAndroidKey { get; set; }
public string AppCenteriOSKey { get; set; }
public string PushNotificationsChannel { get; set; }
public string UpdateFunctionURL { get; set; }
public string TweetFunctionUrl { get; set; }
public static AppConfig GetConfig()
{
#if DEBUG
return new AppConfig()
{
AppCenterAndroidKey = "6f9a7703-8ca4-477e-9558-7e095f7d20aa",
AppCenteriOSKey = "1e7f311f-1055-4ec9-8b00-0302015ab8ae",
PushNotificationsChannel = "AuditUpdateDebug",
UpdateFunctionURL = "https://dotnetruazure.azurewebsites.net/api/Update",
TweetFunctionUrl = "https://dotnettweetservice.azurewebsites.net/api/Tweets"
};
#endif
#pragma warning disable CS0162 // Unreachable code detected
var configBytes = ResourceHelper.ExtractResource("DotNetRu.Utils.Config.config.json");
var configBytesAsString = Encoding.UTF8.GetString(configBytes);
return JsonConvert.DeserializeObject<AppConfig>(configBytesAsString);
#pragma warning restore CS0162 // Unreachable code detected
}
}
}
``` |
bf1268f6-5b3c-4edc-8135-c7e0d029a5ac | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace XamExample {
public partial class MyPage : ContentPage {
public MyPage() {
InitializeComponent();
var c = 0;
XamEffects.TouchEffect.SetColor(plus, Color.White);
XamEffects.Commands.SetTap(plus, new Command(() => {
c++;
counter.Text = $"Touches: {c}";
}));
XamEffects.TouchEffect.SetColor(minus, Color.White);
XamEffects.Commands.SetTap(minus, new Command(() => {
c--;
counter.Text = $"Touches: {c}";
}));
}
}
}
```
Update example, add long tap | ```c#
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace XamExample {
public partial class MyPage : ContentPage {
public MyPage() {
InitializeComponent();
var c = 0;
XamEffects.TouchEffect.SetColor(plus, Color.White);
XamEffects.Commands.SetTap(plus, new Command(() => {
c++;
counter.Text = $"Touches: {c}";
}));
XamEffects.TouchEffect.SetColor(minus, Color.White);
XamEffects.Commands.SetLongTap(minus, new Command(() => {
c--;
counter.Text = $"Touches: {c}";
}));
}
}
}
``` |
740eccc3-7b2b-4d28-961a-e4c988d1fad2 | {
"language": "C#"
} | ```c#
using Mono.TextEditor.Highlighting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xwt.Drawing;
namespace XwtPlus.TextEditor
{
public class TextEditorOptions
{
public Font EditorFont = Font.FromName("Consolas 13");
public IndentStyle IndentStyle = IndentStyle.Auto;
public int TabSize = 4;
public Color Background = Colors.White;
public ColorScheme ColorScheme = SyntaxModeService.DefaultColorStyle;
public bool CurrentLineNumberBold = true;
}
}
```
Set Default Font to something that should be on all systems | ```c#
using Mono.TextEditor.Highlighting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xwt.Drawing;
namespace XwtPlus.TextEditor
{
public class TextEditorOptions
{
public Font EditorFont = Font.SystemMonospaceFont;
public IndentStyle IndentStyle = IndentStyle.Auto;
public int TabSize = 4;
public Color Background = Colors.White;
public ColorScheme ColorScheme = SyntaxModeService.DefaultColorStyle;
public bool CurrentLineNumberBold = true;
}
}
``` |
5221824a-fccd-4c7f-b8a6-dfe02d802c87 | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VersionInfo.cs" company="Dani Michel">
// Dani Michel 2013
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyCompany("Dani Michel")]
[assembly: System.Reflection.AssemblyCopyright("Copyright © 2014")]
[assembly: System.Reflection.AssemblyVersion("0.8.0.*")]
[assembly: System.Reflection.AssemblyInformationalVersion("Belt 0.8.0")]```
Build number removed from the version string, as this creates problems with NuGet dependencies. | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VersionInfo.cs" company="Dani Michel">
// Dani Michel 2013
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyCompany("Dani Michel")]
[assembly: System.Reflection.AssemblyCopyright("Copyright © 2014")]
[assembly: System.Reflection.AssemblyVersion("0.8.1")]
[assembly: System.Reflection.AssemblyInformationalVersion("Belt 0.8.1")]``` |
82d54dd3-2676-48ab-be55-ccc3760d604c | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public abstract class BaseAckMessage : ILiteNetLibMessage
{
public uint ackId;
public AckResponseCode responseCode;
public void Deserialize(NetDataReader reader)
{
ackId = reader.GetUInt();
responseCode = (AckResponseCode)reader.GetByte();
DeserializeData(reader);
}
public void Serialize(NetDataWriter writer)
{
writer.Put(ackId);
writer.Put((byte)responseCode);
SerializeData(writer);
}
public abstract void DeserializeData(NetDataReader reader);
public abstract void SerializeData(NetDataWriter writer);
}
}
```
Make base ack message not abstract | ```c#
using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public class BaseAckMessage : ILiteNetLibMessage
{
public uint ackId;
public AckResponseCode responseCode;
public void Deserialize(NetDataReader reader)
{
ackId = reader.GetUInt();
responseCode = (AckResponseCode)reader.GetByte();
DeserializeData(reader);
}
public void Serialize(NetDataWriter writer)
{
writer.Put(ackId);
writer.Put((byte)responseCode);
SerializeData(writer);
}
public virtual void DeserializeData(NetDataReader reader) { }
public virtual void SerializeData(NetDataWriter writer) { }
}
}
``` |
c4ba2cbd-ef03-442d-9676-199c0f3d12b9 | {
"language": "C#"
} | ```c#
using System;
using System.Net;
using LtiLibrary.Core.Outcomes.v2;
using Newtonsoft.Json;
using Xunit;
namespace LtiLibrary.AspNet.Tests
{
public class LineItemsControllerUnitTests
{
[Fact]
public void GetLineItemBeforePostReturnsNotFound()
{
var controller = new LineItemsController();
ControllerSetup.RegisterContext(controller, "LineItems");
var result = controller.Get(LineItemsController.LineItemId);
Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode);
}
[Fact]
public void PostLineItemReturnsValidLineItem()
{
var controller = new LineItemsController();
ControllerSetup.RegisterContext(controller, "LineItems");
var lineitem = new LineItem
{
LineItemOf = new Context { ContextId = LineItemsController.ContextId },
ReportingMethod = "res:Result"
};
var result = controller.Post(LineItemsController.ContextId, lineitem);
Assert.Equal(HttpStatusCode.Created, result.Result.StatusCode);
var lineItem = JsonConvert.DeserializeObject<LineItem>(result.Result.Content.ReadAsStringAsync().Result);
Assert.NotNull(lineItem);
Assert.Equal(LineItemsController.LineItemId, lineItem.Id.ToString());
}
[Fact]
public void GetLineItemsBeforePostReturnsNotFound()
{
var controller = new LineItemsController();
ControllerSetup.RegisterContext(controller, "LineItems");
var result = controller.Get();
Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode);
}
}
}
```
Add Async suffix to async methods | ```c#
using System;
using System.Net;
using LtiLibrary.Core.Outcomes.v2;
using Newtonsoft.Json;
using Xunit;
namespace LtiLibrary.AspNet.Tests
{
public class LineItemsControllerUnitTests
{
[Fact]
public void GetLineItemBeforePostReturnsNotFound()
{
var controller = new LineItemsController();
ControllerSetup.RegisterContext(controller, "LineItems");
var result = controller.GetAsync(LineItemsController.LineItemId);
Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode);
}
[Fact]
public void PostLineItemReturnsValidLineItem()
{
var controller = new LineItemsController();
ControllerSetup.RegisterContext(controller, "LineItems");
var lineitem = new LineItem
{
LineItemOf = new Context { ContextId = LineItemsController.ContextId },
ReportingMethod = "res:Result"
};
var result = controller.PostAsync(LineItemsController.ContextId, lineitem);
Assert.Equal(HttpStatusCode.Created, result.Result.StatusCode);
var lineItem = JsonConvert.DeserializeObject<LineItem>(result.Result.Content.ReadAsStringAsync().Result);
Assert.NotNull(lineItem);
Assert.Equal(LineItemsController.LineItemId, lineItem.Id.ToString());
}
[Fact]
public void GetLineItemsBeforePostReturnsNotFound()
{
var controller = new LineItemsController();
ControllerSetup.RegisterContext(controller, "LineItems");
var result = controller.GetAsync();
Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode);
}
}
}
``` |
45dc2d28-1726-437c-93e2-11fd0b08d906 | {
"language": "C#"
} | ```c#
namespace Slinqy.Test.Functional.Utilities.Polling
{
using System;
using System.Diagnostics;
using System.Threading;
/// <summary>
/// Provides common polling functionality.
/// </summary>
internal static class Poll
{
/// <summary>
/// Polls the specified function until a certain criteria is met.
/// </summary>
/// <typeparam name="T">Specifies the return type of the from function.</typeparam>
/// <param name="from">Specifies the function to use to retrieve the value.</param>
/// <param name="until">Specifies the function to use to test the value.</param>
/// <param name="interval">Specifies how often to get the latest value via the from function.</param>
/// <param name="maxPollDuration">Specifies the max amount of time to wait for the right value before giving up.</param>
public
static
void
Value<T>(
Func<T> from,
Func<T, bool> until,
TimeSpan interval,
TimeSpan maxPollDuration)
{
var stopwatch = Stopwatch.StartNew();
while (until(from()))
{
if (stopwatch.Elapsed > maxPollDuration)
throw new PollTimeoutException(maxPollDuration);
Thread.Sleep(interval);
}
}
}
}
```
Fix bug in polling logic. | ```c#
namespace Slinqy.Test.Functional.Utilities.Polling
{
using System;
using System.Diagnostics;
using System.Threading;
/// <summary>
/// Provides common polling functionality.
/// </summary>
internal static class Poll
{
/// <summary>
/// Polls the specified function until a certain criteria is met.
/// </summary>
/// <typeparam name="T">Specifies the return type of the from function.</typeparam>
/// <param name="from">Specifies the function to use to retrieve the value.</param>
/// <param name="until">Specifies the function to use to test the value.</param>
/// <param name="interval">Specifies how often to get the latest value via the from function.</param>
/// <param name="maxPollDuration">Specifies the max amount of time to wait for the right value before giving up.</param>
public
static
void
Value<T>(
Func<T> from,
Func<T, bool> until,
TimeSpan interval,
TimeSpan maxPollDuration)
{
var stopwatch = Stopwatch.StartNew();
while (until(from()) == false)
{
if (stopwatch.Elapsed > maxPollDuration)
throw new PollTimeoutException(maxPollDuration);
Thread.Sleep(interval);
}
}
}
}
``` |
3705e382-e195-4c32-a349-f03935a3e231 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
namespace NLogger
{
public class CustomLogFactory<T> where T : NLoggerSection
{
private readonly List<ILogWriterRegistration<T>> _logWriterTypes;
public CustomLogFactory()
{
_logWriterTypes= new List<ILogWriterRegistration<T>>();
}
public void RegisterLogWriterType(ILogWriterRegistration<T> registration)
{
_logWriterTypes.Add(registration);
}
/// <summary>
/// Create a logger using App.config or Web.config settings
/// </summary>
/// <returns></returns>
public ILogger CreateLogger(string sectionName)
{
var config = (T) ConfigurationManager.GetSection(sectionName);
if (config != null)
{
var writer = GetLogWriter(config);
if (writer != null)
{
return new Logger(writer, config.LogLevel);
}
}
return LoggerFactory.CreateLogger(config);
}
private ILogWriter GetLogWriter(T config)
{
var type = _logWriterTypes.FirstOrDefault(t => t.HasSection(config));
return type != null
? type.GetWriter(config)
: null;
}
}
}
```
Support config from alternative source | ```c#
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
namespace NLogger
{
public class CustomLogFactory<T> where T : NLoggerSection
{
private readonly List<ILogWriterRegistration<T>> _logWriterTypes;
public CustomLogFactory()
{
_logWriterTypes= new List<ILogWriterRegistration<T>>();
}
public void RegisterLogWriterType(ILogWriterRegistration<T> registration)
{
_logWriterTypes.Add(registration);
}
public ILogger CreateLogger(string sectionName, Configuration configFile)
{
var config = (T)configFile.GetSection(sectionName);
return CreateLogger(config);
}
/// <summary>
/// Create a logger using App.config or Web.config settings
/// </summary>
/// <returns></returns>
public ILogger CreateLogger(string sectionName)
{
var config = (T) ConfigurationManager.GetSection(sectionName);
return CreateLogger(config);
}
private ILogger CreateLogger(T config)
{
if (config != null)
{
var writer = GetLogWriter(config);
if (writer != null)
{
return new Logger(writer, config.LogLevel);
}
}
return LoggerFactory.CreateLogger(config);
}
private ILogWriter GetLogWriter(T config)
{
var type = _logWriterTypes.FirstOrDefault(t => t.HasSection(config));
return type != null
? type.GetWriter(config)
: null;
}
}
}
``` |
3d2f9dd4-4400-4242-afcf-2b92007104d4 | {
"language": "C#"
} | ```c#
using System;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Ide.Editor.Extension;
namespace JustEnoughVi
{
public abstract class ViMode
{
protected TextEditor Editor { get; set; }
public Mode RequestedMode { get; internal set; }
protected ViMode(TextEditor editor)
{
Editor = editor;
RequestedMode = Mode.None;
}
public abstract void Activate();
public abstract void Deactivate();
public abstract bool KeyPress (KeyDescriptor descriptor);
protected void SetSelectLines(int start, int end)
{
var startLine = start > end ? Editor.GetLine(end) : Editor.GetLine(start);
var endLine = start > end ? Editor.GetLine(start) : Editor.GetLine(end);
Editor.SetSelection(startLine.Offset, endLine.EndOffsetIncludingDelimiter);
}
}
}
```
Handle overflows in line selection | ```c#
using System;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Ide.Editor.Extension;
namespace JustEnoughVi
{
public abstract class ViMode
{
protected TextEditor Editor { get; set; }
public Mode RequestedMode { get; internal set; }
protected ViMode(TextEditor editor)
{
Editor = editor;
RequestedMode = Mode.None;
}
public abstract void Activate();
public abstract void Deactivate();
public abstract bool KeyPress (KeyDescriptor descriptor);
protected void SetSelectLines(int start, int end)
{
start = Math.Min(start, Editor.LineCount);
end = Math.Min(end, Editor.LineCount);
var startLine = start > end ? Editor.GetLine(end) : Editor.GetLine(start);
var endLine = start > end ? Editor.GetLine(start) : Editor.GetLine(end);
Editor.SetSelection(startLine.Offset, endLine.EndOffsetIncludingDelimiter);
}
}
}
``` |
7bccf511-beec-4c13-84a2-77cb7481c4be | {
"language": "C#"
} | ```c#
using System.IO;
using Umbraco.Core.Configuration;
namespace Umbraco.Core.IO
{
public class SystemFiles
{
public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config";
public static string TelemetricsIdentifier => SystemDirectories.Umbraco + "/telemetrics-id.umb";
// TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache
public static string GetContentCacheXml(IGlobalSettings globalSettings)
{
return Path.Combine(globalSettings.LocalTempPath, "umbraco.config");
}
}
}
```
Move marker file into App_Data a folder that can never be served | ```c#
using System.IO;
using Umbraco.Core.Configuration;
namespace Umbraco.Core.IO
{
public class SystemFiles
{
public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config";
public static string TelemetricsIdentifier => SystemDirectories.Data + "/telemetrics-id.umb";
// TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache
public static string GetContentCacheXml(IGlobalSettings globalSettings)
{
return Path.Combine(globalSettings.LocalTempPath, "umbraco.config");
}
}
}
``` |
eaad9d00-15d6-4add-bc2f-a42c606a6228 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Mono.Nat
{
public static class SemaphoreSlimExtensions
{
class SemaphoreSlimDisposable : IDisposable
{
SemaphoreSlim Semaphore;
public SemaphoreSlimDisposable (SemaphoreSlim semaphore)
{
Semaphore = semaphore;
}
public void Dispose ()
{
Semaphore?.Release ();
Semaphore = null;
}
}
public static async Task<IDisposable> DisposableWaitAsync (this SemaphoreSlim semaphore)
{
await semaphore.WaitAsync ();
return new SemaphoreSlimDisposable (semaphore);
}
}
}
```
Make this internal. It's not supposed to be part of the API | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Mono.Nat
{
static class SemaphoreSlimExtensions
{
class SemaphoreSlimDisposable : IDisposable
{
SemaphoreSlim Semaphore;
public SemaphoreSlimDisposable (SemaphoreSlim semaphore)
{
Semaphore = semaphore;
}
public void Dispose ()
{
Semaphore?.Release ();
Semaphore = null;
}
}
public static async Task<IDisposable> DisposableWaitAsync (this SemaphoreSlim semaphore)
{
await semaphore.WaitAsync ();
return new SemaphoreSlimDisposable (semaphore);
}
}
}
``` |
bba1ce9f-e103-4518-adb4-ce8fdd3b6caa | {
"language": "C#"
} | ```c#
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project. Project-level
// suppressions either have no target or are given a specific target
// and scoped to a namespace, type, member, etc.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click "In Project
// Suppression File". You do not need to add suppressions to this
// file manually.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.Providers")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.ToolsOptionsUI")]
```
Add supression for generated xaml class | ```c#
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project. Project-level
// suppressions either have no target or are given a specific target
// and scoped to a namespace, type, member, etc.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click "In Project
// Suppression File". You do not need to add suppressions to this
// file manually.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.Providers")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.ToolsOptionsUI")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "XamlGeneratedNamespace")]
``` |
b5e0123e-ff4e-4563-93fd-0da7e930a025 | {
"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.Generic;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoom
{
private object writeLock = new object();
public long RoomID { get; set; }
public MultiplayerRoomState State { get; set; }
private List<MultiplayerRoomUser> users = new List<MultiplayerRoomUser>();
public IReadOnlyList<MultiplayerRoomUser> Users
{
get
{
lock (writeLock)
return users.ToArray();
}
}
public void Join(int user)
{
lock (writeLock)
users.Add(new MultiplayerRoomUser(user));
}
public void Leave(int user)
{
lock (writeLock)
users.RemoveAll(u => u.UserID == user);
}
}
}
```
Add locking on join/leave operations | ```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.Generic;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoom
{
private object writeLock = new object();
public long RoomID { get; set; }
public MultiplayerRoomState State { get; set; }
private List<MultiplayerRoomUser> users = new List<MultiplayerRoomUser>();
public IReadOnlyList<MultiplayerRoomUser> Users
{
get
{
lock (writeLock)
return users.ToArray();
}
}
public MultiplayerRoomUser Join(int userId)
{
var user = new MultiplayerRoomUser(userId);
lock (writeLock) users.Add(user);
return user;
}
public MultiplayerRoomUser Leave(int userId)
{
lock (writeLock)
{
var user = users.Find(u => u.UserID == userId);
if (user == null)
return null;
users.Remove(user);
return user;
}
}
}
}
``` |
76099741-99e1-4914-8cf3-fa875d868420 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using Mitternacht.Services;
using NLog;
namespace Mitternacht.Modules.Forum.Services {
public class ForumService : IMService {
private readonly IBotCredentials _creds;
private readonly Logger _log;
public GommeHDnetForumAPI.Forum Forum { get; private set; }
public bool HasForumInstance => Forum != null;
public bool LoggedIn => Forum?.LoggedIn ?? false;
private Task _loginTask;
public ForumService(IBotCredentials creds) {
_creds = creds;
_log = LogManager.GetCurrentClassLogger();
InitForumInstance();
}
public void InitForumInstance() {
_loginTask?.Dispose();
_loginTask = Task.Run(() => {
try {
Forum = new GommeHDnetForumAPI.Forum(_creds.ForumUsername, _creds.ForumPassword);
_log.Info($"Initialized new Forum instance.");
} catch(Exception e) {
_log.Warn(e, $"Initializing new Forum instance failed.");
}
});
}
}
}```
Print information about the exception when the bot fails to log in to the forum. | ```c#
using System;
using System.Threading.Tasks;
using Mitternacht.Services;
using NLog;
namespace Mitternacht.Modules.Forum.Services {
public class ForumService : IMService {
private readonly IBotCredentials _creds;
private readonly Logger _log;
public GommeHDnetForumAPI.Forum Forum { get; private set; }
public bool HasForumInstance => Forum != null;
public bool LoggedIn => Forum?.LoggedIn ?? false;
private Task _loginTask;
public ForumService(IBotCredentials creds) {
_creds = creds;
_log = LogManager.GetCurrentClassLogger();
InitForumInstance();
}
public void InitForumInstance() {
_loginTask?.Dispose();
_loginTask = Task.Run(() => {
try {
Forum = new GommeHDnetForumAPI.Forum(_creds.ForumUsername, _creds.ForumPassword);
_log.Info($"Initialized new Forum instance.");
} catch(Exception e) {
_log.Warn(e, $"Initializing new Forum instance failed: {e}");
}
});
}
}
}``` |
4c1a7a59-3b5f-44ff-b76f-36bbcd7e411c | {
"language": "C#"
} | ```c#
using System;
using Grpc.Core;
using Hello;
namespace HelloClient
{
class Program
{
public static void Main(string[] args)
{
Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
var client = new HelloService.HelloServiceClient(channel);
String user = "Euler";
var reply = client.SayHello(new HelloReq { Name = user });
Console.WriteLine(reply.Result);
channel.ShutdownAsync().Wait();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
```
Add error handling for the client | ```c#
using System;
using Grpc.Core;
using Hello;
namespace HelloClient
{
class Program
{
public static void Main(string[] args)
{
Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
var client = new HelloService.HelloServiceClient(channel);
// ideally you should check for errors here too
var reply = client.SayHello(new HelloReq { Name = "Euler" });
Console.WriteLine(reply.Result);
try
{
reply = client.SayHelloStrict(new HelloReq { Name = "Leonhard Euler" });
Console.WriteLine(reply.Result);
}
catch (RpcException e)
{
// ouch!
// lets print the gRPC error message
// which is "Length of `Name` cannot be more than 10 characters"
Console.WriteLine(e.Status.Detail);
// lets access the error code, which is `INVALID_ARGUMENT`
Console.WriteLine(e.Status.StatusCode);
// Want its int version for some reason?
// you shouldn't actually do this, but if you need for debugging,
// you can access `e.Status.StatusCode` which will give you `3`
Console.WriteLine((int)e.Status.StatusCode);
// Want to take specific action based on specific error?
if (e.Status.StatusCode == Grpc.Core.StatusCode.InvalidArgument) {
// do your thing
}
}
channel.ShutdownAsync().Wait();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
``` |
cb9256fb-a165-4ccf-a6e8-60d7076f1a13 | {
"language": "C#"
} | ```c#
@model IEnumerable<Article>
@{
ViewData["Title"] = "Home Page";
}
<div class="header clearfix">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" class="active"><a href="/">Home</a></li>
<li role="presentation"><a href="https://kenticocloud.com/" target="_blank">Kentico Cloud</a></li>
<li role="presentation"><a href="https://app.kenticocloud.com/sign-up" target="_blank">Sign up</a></li>
</ul>
</nav>
<h3 class="text-muted">Kentico Cloud Boilerplate</h3>
</div>
<div class="jumbotron">
<h1>Let's Get Started</h1>
<p class="lead">This boilerplate includes a set of features and best practices to kick off your website development with Kentico Cloud smoothly. Take a look into the code how this page works.</p>
<p><a class="btn btn-lg btn-success" href="https://github.com/Kentico/cloud-boilerplate-net#quick-start" target="_blank" role="button">Read the Quick Start</a></p>
</div>
<div class="row marketing">
<h2>Articles from the Dancing Goat Sample Site</h2>
</div>
<div class="row marketing">
@*
This MVC helper method ensures that current model is rendered
with suitable view from /Views/Shared/DisplayTemplates
*@
@Html.DisplayForModel()
</div>
```
Correct copy on the home page | ```c#
@model IEnumerable<Article>
@{
ViewData["Title"] = "Home Page";
}
<div class="header clearfix">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" class="active"><a href="/">Home</a></li>
<li role="presentation"><a href="https://kenticocloud.com/" target="_blank">Kentico Cloud</a></li>
<li role="presentation"><a href="https://app.kenticocloud.com/sign-up" target="_blank">Sign up</a></li>
</ul>
</nav>
<h3 class="text-muted">Kentico Cloud Boilerplate</h3>
</div>
<div class="jumbotron">
<h1>Let's Get Started</h1>
<p class="lead">This boilerplate includes a set of features and best practices to kick off your website development with Kentico Cloud smoothly. Take a look into the code to see how it works.</p>
<p><a class="btn btn-lg btn-success" href="https://github.com/Kentico/cloud-boilerplate-net#quick-start" target="_blank" role="button">Read the Quick Start</a></p>
</div>
<div class="row marketing">
<h2>Articles from the Dancing Goat Sample Site</h2>
</div>
<div class="row marketing">
@*
This MVC helper method ensures that current model is rendered
with suitable view from /Views/Shared/DisplayTemplates
*@
@Html.DisplayForModel()
</div>
``` |
e5831c67-d004-472f-8973-56a02f9c7052 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
internal class StackSerializationDelegateProvider : SerializationDelegateProviderBase
{
public override bool CanHandle(Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>);
}
private static JsonValue _Encode<T>(Stack<T> stack, JsonSerializer serializer)
{
var array = new JsonArray();
for (int i = 0; i < stack.Count; i++)
{
array.Add(serializer.Serialize(stack.ElementAt(i)));
}
return array;
}
private static Stack<T> _Decode<T>(JsonValue json, JsonSerializer serializer)
{
var stack = new Stack<T>();
for (int i = 0; i < json.Array.Count; i++)
{
stack.Push(serializer.Deserialize<T>(json.Array[i]));
}
return stack;
}
}
}```
Decrease allocations in stack serializer | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
internal class StackSerializationDelegateProvider : SerializationDelegateProviderBase
{
public override bool CanHandle(Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>);
}
private static JsonValue _Encode<T>(Stack<T> stack, JsonSerializer serializer)
{
var values = new JsonValue[stack.Count];
for (int i = 0; i < values.Length; i++)
{
values[0] = serializer.Serialize(stack.ElementAt(i));
}
return new JsonArray(values);
}
private static Stack<T> _Decode<T>(JsonValue json, JsonSerializer serializer)
{
var array = json.Array;
var values = new T[array.Count];
for (int i = 0; i < values.Length; i++)
{
values[i] = serializer.Deserialize<T>(array[i]);
}
return new Stack<T>(values);
}
}
}``` |
51e6e09c-a48b-4f8e-82e0-3b955077096a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace HeadRaceTimingSite.Models
{
public class Crew
{
public int CrewId { get; set; }
public string Name { get; set; }
public int StartNumber { get; set; }
public List<Result> Results { get; set; }
public int CompetitionId { get; set; }
public Competition Competition { get; set; }
}
}
```
Add method to calculate time | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace HeadRaceTimingSite.Models
{
public class Crew
{
public int CrewId { get; set; }
public string Name { get; set; }
public int StartNumber { get; set; }
public TimeSpan? RunTime(TimingPoint startPoint, TimingPoint finishPoint)
{
Result start = Results.First(r => r.TimingPointId == startPoint.TimingPointId);
Result finish = Results.First(r => r.TimingPointId == finishPoint.TimingPointId);
if (start != null && finish != null)
return finish.TimeOfDay - start.TimeOfDay;
else
return null;
}
public List<Result> Results { get; set; }
public int CompetitionId { get; set; }
public Competition Competition { get; set; }
}
}
``` |
b1707cd0-87ee-4489-94e0-234a49e02279 | {
"language": "C#"
} | ```c#
#if NETFX_CORE
namespace HelixToolkit.UWP
#else
namespace HelixToolkit.Wpf.SharpDX
#endif
{
using Model.Scene;
/// <summary>
/// Highlight the border of meshes
/// </summary>
public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur
{
protected override SceneNode OnCreateSceneNode()
{
return new NodePostEffectMeshOutlineBlur();
}
}
}
```
Fix border highlight effects gets the wrong effect node | ```c#
#if NETFX_CORE
namespace HelixToolkit.UWP
#else
namespace HelixToolkit.Wpf.SharpDX
#endif
{
using Model.Scene;
/// <summary>
/// Highlight the border of meshes
/// </summary>
public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur
{
protected override SceneNode OnCreateSceneNode()
{
return new NodePostEffectBorderHighlight();
}
}
}
``` |
b7ac3317-367a-4ada-8321-caf8df940743 | {
"language": "C#"
} | ```c#
#region Copyright 2014 Exceptionless
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// http://www.gnu.org/licenses/agpl-3.0.html
#endregion
using System;
using System.Threading.Tasks;
using CodeSmith.Core.Component;
using Exceptionless.Core.Messaging;
using Exceptionless.Core.Messaging.Models;
using Exceptionless.Core.Plugins.EventProcessor;
namespace Exceptionless.Core.Pipeline {
[Priority(80)]
public class NotifySignalRAction : EventPipelineActionBase {
private readonly IMessagePublisher _publisher;
public NotifySignalRAction(IMessagePublisher publisher) {
_publisher = publisher;
}
protected override bool ContinueOnError {
get { return true; }
}
public override void Process(EventContext ctx) {
Task.Factory.StartNewDelayed(1000, () => _publisher.Publish(new EventOccurrence {
Id = ctx.Event.Id,
OrganizationId = ctx.Event.OrganizationId,
ProjectId = ctx.Event.ProjectId,
StackId = ctx.Event.StackId,
Type = ctx.Event.Type,
IsHidden = ctx.Event.IsHidden,
IsFixed = ctx.Event.IsFixed,
IsNotFound = ctx.Event.IsNotFound(),
IsRegression = ctx.IsRegression
}));
}
}
}```
Increase the message notification delay slightly. | ```c#
#region Copyright 2014 Exceptionless
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// http://www.gnu.org/licenses/agpl-3.0.html
#endregion
using System;
using System.Threading.Tasks;
using CodeSmith.Core.Component;
using Exceptionless.Core.Messaging;
using Exceptionless.Core.Messaging.Models;
using Exceptionless.Core.Plugins.EventProcessor;
namespace Exceptionless.Core.Pipeline {
[Priority(80)]
public class NotifySignalRAction : EventPipelineActionBase {
private readonly IMessagePublisher _publisher;
public NotifySignalRAction(IMessagePublisher publisher) {
_publisher = publisher;
}
protected override bool ContinueOnError {
get { return true; }
}
public override void Process(EventContext ctx) {
Task.Factory.StartNewDelayed(1500, () => _publisher.Publish(new EventOccurrence {
Id = ctx.Event.Id,
OrganizationId = ctx.Event.OrganizationId,
ProjectId = ctx.Event.ProjectId,
StackId = ctx.Event.StackId,
Type = ctx.Event.Type,
IsHidden = ctx.Event.IsHidden,
IsFixed = ctx.Event.IsFixed,
IsNotFound = ctx.Event.IsNotFound(),
IsRegression = ctx.IsRegression
}));
}
}
}``` |
f76f86d9-aa97-4f6b-8814-aecf43b1e2d1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Battlezeppelins.Models;
namespace Battlezeppelins.Controllers
{
public class GameController : BaseController
{
public ActionResult Metadata()
{
Game game = Game.GetInstance(base.GetPlayer());
if (game != null)
{
return Json(new { playing = true, opponent = game.opponent.name }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { playing = false }, JsonRequestBehavior.AllowGet);
}
}
public ActionResult Surrender()
{
Game game = Game.GetInstance(base.GetPlayer());
if (game != null)
{
game.Surrender();
}
return null;
}
public ActionResult AddZeppelin()
{
Game game = Game.GetInstance(base.GetPlayer());
string typeStr = Request.Form["type"];
ZeppelinType type = (ZeppelinType)Enum.Parse(typeof(ZeppelinType), typeStr, true);
int x = Int32.Parse(Request.Form["x"]);
int y = Int32.Parse(Request.Form["y"]);
bool rotDown = Boolean.Parse(Request.Form["rotDown"]);
Zeppelin zeppelin = new Zeppelin(type, x, y, rotDown);
bool zeppelinAdded = game.AddZeppelin(zeppelin);
return Json(zeppelinAdded, JsonRequestBehavior.AllowGet);
}
}
}
```
Send game state to client. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Battlezeppelins.Models;
namespace Battlezeppelins.Controllers
{
public class GameController : BaseController
{
public ActionResult Metadata()
{
Game game = Game.GetInstance(base.GetPlayer());
if (game != null)
{
return Json(new {
playing = true,
opponent = game.opponent.name,
gameState = game.gameState.ToString() }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { playing = false }, JsonRequestBehavior.AllowGet);
}
}
public ActionResult Surrender()
{
Game game = Game.GetInstance(base.GetPlayer());
if (game != null)
{
game.Surrender();
}
return null;
}
public ActionResult AddZeppelin()
{
Game game = Game.GetInstance(base.GetPlayer());
string typeStr = Request.Form["type"];
ZeppelinType type = (ZeppelinType)Enum.Parse(typeof(ZeppelinType), typeStr, true);
int x = Int32.Parse(Request.Form["x"]);
int y = Int32.Parse(Request.Form["y"]);
bool rotDown = Boolean.Parse(Request.Form["rotDown"]);
Zeppelin zeppelin = new Zeppelin(type, x, y, rotDown);
bool zeppelinAdded = game.AddZeppelin(zeppelin);
return Json(zeppelinAdded, JsonRequestBehavior.AllowGet);
}
}
}
``` |
dcb51fe4-391e-4898-aa12-8d449a23ce80 | {
"language": "C#"
} | ```c#
namespace Ductus.FluentDocker.Model.HostEvents
{
/// <summary>
/// Base evnet emitte by the docker dameon using e.g. docker events.
/// </summary>
/// <remarks>
/// See docker documentation https://docs.docker.com/engine/reference/commandline/events/
/// </remarks>
public class Event
{
/// <summary>
/// The type of the event.
/// </summary>
public EventType Type { get; set; }
/// <summary>
/// The event action
/// </summary>
public EventAction Action { get; set; }
}
}
```
Fix formatting in events so it will build | ```c#
namespace Ductus.FluentDocker.Model.HostEvents
{
/// <summary>
/// Base evnet emitte by the docker dameon using e.g. docker events.
/// </summary>
/// <remarks>
/// See docker documentation https://docs.docker.com/engine/reference/commandline/events/
/// </remarks>
public class Event
{
/// <summary>
/// The type of the event.
/// </summary>
public EventType Type { get; set; }
/// <summary>
/// The event action
/// </summary>
public EventAction Action { get; set; }
}
}
``` |
042b0b3f-e4c3-4b5d-af28-5051a03b7cba | {
"language": "C#"
} | ```c#
namespace FakeItEasy.Core
{
using System;
using static FakeItEasy.ObjectMembers;
internal class StrictFakeRule : IFakeObjectCallRule
{
private readonly StrictFakeOptions options;
public StrictFakeRule(StrictFakeOptions options)
{
this.options = options;
}
public int? NumberOfTimesToCall => null;
public bool IsApplicableTo(IFakeObjectCall fakeObjectCall)
{
if (fakeObjectCall.Method.IsSameMethodAs(EqualsMethod))
{
return !this.HasOption(StrictFakeOptions.AllowEquals);
}
if (fakeObjectCall.Method.IsSameMethodAs(GetHashCodeMethod))
{
return !this.HasOption(StrictFakeOptions.AllowGetHashCode);
}
if (fakeObjectCall.Method.IsSameMethodAs(ToStringMethod))
{
return !this.HasOption(StrictFakeOptions.AllowToString);
}
if (EventCall.TryGetEventCall(fakeObjectCall, out _))
{
return !this.HasOption(StrictFakeOptions.AllowEvents);
}
return true;
}
public void Apply(IInterceptedFakeObjectCall fakeObjectCall)
{
string message = ExceptionMessages.CallToUnconfiguredMethodOfStrictFake(fakeObjectCall);
if (EventCall.TryGetEventCall(fakeObjectCall, out _))
{
message += Environment.NewLine + ExceptionMessages.HandleEventsOnStrictFakes;
}
throw new ExpectationException(message);
}
private bool HasOption(StrictFakeOptions flag) => (flag & this.options) == flag;
}
}
```
Allow strict Fake to permit access to overridden Object methods | ```c#
namespace FakeItEasy.Core
{
using System;
using static FakeItEasy.ObjectMembers;
internal class StrictFakeRule : IFakeObjectCallRule
{
private readonly StrictFakeOptions options;
public StrictFakeRule(StrictFakeOptions options)
{
this.options = options;
}
public int? NumberOfTimesToCall => null;
public bool IsApplicableTo(IFakeObjectCall fakeObjectCall)
{
if (fakeObjectCall.Method.HasSameBaseMethodAs(EqualsMethod))
{
return !this.HasOption(StrictFakeOptions.AllowEquals);
}
if (fakeObjectCall.Method.HasSameBaseMethodAs(GetHashCodeMethod))
{
return !this.HasOption(StrictFakeOptions.AllowGetHashCode);
}
if (fakeObjectCall.Method.HasSameBaseMethodAs(ToStringMethod))
{
return !this.HasOption(StrictFakeOptions.AllowToString);
}
if (EventCall.TryGetEventCall(fakeObjectCall, out _))
{
return !this.HasOption(StrictFakeOptions.AllowEvents);
}
return true;
}
public void Apply(IInterceptedFakeObjectCall fakeObjectCall)
{
string message = ExceptionMessages.CallToUnconfiguredMethodOfStrictFake(fakeObjectCall);
if (EventCall.TryGetEventCall(fakeObjectCall, out _))
{
message += Environment.NewLine + ExceptionMessages.HandleEventsOnStrictFakes;
}
throw new ExpectationException(message);
}
private bool HasOption(StrictFakeOptions flag) => (flag & this.options) == flag;
}
}
``` |
0865d887-2cfe-4d2f-873d-e56dcf449d0f | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OpenKh.Tools.LayoutViewer {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Drawing.Color BackgroundColor {
get {
return ((global::System.Drawing.Color)(this["BackgroundColor"]));
}
set {
this["BackgroundColor"] = value;
}
}
}
}
```
Set default value to BackgroundColor | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OpenKh.Tools.LayoutViewer {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValue("Magenta")]
public global::System.Drawing.Color BackgroundColor {
get {
return ((global::System.Drawing.Color)(this["BackgroundColor"]));
}
set {
this["BackgroundColor"] = value;
}
}
}
}
``` |
4844e15c-153b-415c-9b83-bad8dae972de | {
"language": "C#"
} | ```c#
using Espera.Network;
using Newtonsoft.Json;
using System;
namespace Espera.Core
{
public class SoundCloudSong : Song
{
public SoundCloudSong()
: base(String.Empty, TimeSpan.Zero)
{ }
[JsonProperty("artwork_url")]
public Uri ArtworkUrl { get; set; }
public string Description { get; set; }
[JsonProperty("duration")]
public int DurationMilliseconds
{
get { return (int)this.Duration.TotalMilliseconds; }
set { this.Duration = TimeSpan.FromMilliseconds(value); }
}
public int Id { get; set; }
[JsonProperty("streamable")]
public bool IsStreamable { get; set; }
public override bool IsVideo
{
get { return false; }
}
public override NetworkSongSource NetworkSongSource
{
get { return NetworkSongSource.Youtube; }
}
[JsonProperty("permalink_url")]
public Uri PermaLinkUrl
{
get { return new Uri(this.OriginalPath); }
set { this.OriginalPath = value.ToString(); }
}
[JsonProperty("stream_url")]
public Uri StreamUrl
{
get { return new Uri(this.PlaybackPath); }
set { this.PlaybackPath = value.ToString(); }
}
public User User { get; set; }
}
public class User
{
public string Username { get; set; }
}
}```
Set the artist to the username | ```c#
using Espera.Network;
using Newtonsoft.Json;
using System;
namespace Espera.Core
{
public class SoundCloudSong : Song
{
private User user;
public SoundCloudSong()
: base(String.Empty, TimeSpan.Zero)
{ }
[JsonProperty("artwork_url")]
public Uri ArtworkUrl { get; set; }
public string Description { get; set; }
[JsonProperty("duration")]
public int DurationMilliseconds
{
get { return (int)this.Duration.TotalMilliseconds; }
set { this.Duration = TimeSpan.FromMilliseconds(value); }
}
public int Id { get; set; }
[JsonProperty("streamable")]
public bool IsStreamable { get; set; }
public override bool IsVideo
{
get { return false; }
}
public override NetworkSongSource NetworkSongSource
{
get { return NetworkSongSource.Youtube; }
}
[JsonProperty("permalink_url")]
public Uri PermaLinkUrl
{
get { return new Uri(this.OriginalPath); }
set { this.OriginalPath = value.ToString(); }
}
[JsonProperty("stream_url")]
public Uri StreamUrl
{
get { return new Uri(this.PlaybackPath); }
set { this.PlaybackPath = value.ToString(); }
}
public User User
{
get { return this.user; }
set
{
this.user = value;
this.Artist = value.Username;
}
}
}
public class User
{
public string Username { get; set; }
}
}``` |
9b39dda0-980f-4cb3-8001-046c6b0c96b9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinUsbInit
{
class DeviceArrivalListener : NativeWindow
{
// Constant value was found in the "windows.h" header file.
private const int WM_DEVICECHANGE = 537;
private const int DBT_DEVICEARRIVAL = 0x8000;
private readonly WinUsbInitForm _parent;
public DeviceArrivalListener(WinUsbInitForm parent)
{
parent.HandleCreated += OnHandleCreated;
parent.HandleDestroyed += OnHandleDestroyed;
_parent = parent;
}
// Listen for the control's window creation and then hook into it.
internal void OnHandleCreated(object sender, EventArgs e)
{
// Window is now created, assign handle to NativeWindow.
AssignHandle(((WinUsbInitForm)sender).Handle);
}
internal void OnHandleDestroyed(object sender, EventArgs e)
{
// Window was destroyed, release hook.
ReleaseHandle();
}
protected override void WndProc(ref Message m)
{
// Listen for operating system messages
if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL)
{
// Notify the form that this message was received.
_parent.DeviceInserted();
}
base.WndProc(ref m);
}
}
}
```
Change WM_DEVICECHANGE value to hexadecimal | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinUsbInit
{
class DeviceArrivalListener : NativeWindow
{
// Constant values was found in the "windows.h" header file.
private const int WM_DEVICECHANGE = 0x219;
private const int DBT_DEVICEARRIVAL = 0x8000;
private readonly WinUsbInitForm _parent;
public DeviceArrivalListener(WinUsbInitForm parent)
{
parent.HandleCreated += OnHandleCreated;
parent.HandleDestroyed += OnHandleDestroyed;
_parent = parent;
}
// Listen for the control's window creation and then hook into it.
internal void OnHandleCreated(object sender, EventArgs e)
{
// Window is now created, assign handle to NativeWindow.
AssignHandle(((WinUsbInitForm)sender).Handle);
}
internal void OnHandleDestroyed(object sender, EventArgs e)
{
// Window was destroyed, release hook.
ReleaseHandle();
}
protected override void WndProc(ref Message m)
{
// Listen for operating system messages
if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL)
{
// Notify the form that this message was received.
_parent.DeviceInserted();
}
base.WndProc(ref m);
}
}
}
``` |
dd329dee-cb10-4768-86b9-4d152d7ff6ea | {
"language": "C#"
} | ```c#
using System;
using Gtk;
namespace LynnaLab
{
[System.ComponentModel.ToolboxItem(true)]
public partial class SpinButtonHexadecimal : Gtk.SpinButton
{
public SpinButtonHexadecimal() : base(0,100,1)
{
this.Numeric = false;
}
protected override int OnOutput() {
this.Numeric = false;
Text = "0x" + ValueAsInt.ToString("X" + Digits);
return 1;
}
protected override int OnInput(out double value) {
try {
value = Convert.ToInt32(Text);
}
catch (Exception e) {
try {
value = Convert.ToInt32(Text.Substring(2),16);
}
catch (Exception) {
value = Value;
}
}
return 1;
}
}
}
```
Use $ for hex symbol to match wla | ```c#
using System;
using Gtk;
namespace LynnaLab
{
[System.ComponentModel.ToolboxItem(true)]
public partial class SpinButtonHexadecimal : Gtk.SpinButton
{
public SpinButtonHexadecimal() : base(0,100,1)
{
this.Numeric = false;
}
protected override int OnOutput() {
this.Numeric = false;
Text = "$" + ValueAsInt.ToString("X" + Digits);
return 1;
}
protected override int OnInput(out double value) {
string text = Text.Trim();
bool success = false;
value = Value;
try {
value = Convert.ToInt32(text);
success = true;
}
catch (Exception e) {
}
try {
if (text.Length > 0 && text[0] == '$') {
value = Convert.ToInt32(text.Substring(1),16);
success = true;
}
}
catch (Exception) {
}
if (!success)
value = Value;
return 1;
}
}
}
``` |
374b24d8-caf6-4c3e-9c71-a28c7952700d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace Graph
{
/// <summary>
/// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>.
/// </summary>
/// <typeparam name="V">
/// The type used to create vertex (node) labels.
/// </typeparam>
/// <typeparam name="W">
/// The type used for the edge weight.
/// </typeparam>
public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>>
where V : struct, IEquatable<V>
where W : struct, IComparable<W>, IEquatable<W>
{
/// <summary>
/// The vertices comprising the <see cref="IUndirectedEdge{V}"/>.
/// </summary>
ISet<V> Vertices { get; }
}
}
```
Fix signature of undirected edge | ```c#
using System;
using System.Collections.Generic;
namespace Graph
{
/// <summary>
/// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>.
/// </summary>
/// <typeparam name="V">
/// The type used to create vertex (node) labels.
/// </typeparam>
/// <typeparam name="W">
/// The type used for the edge weight.
/// </typeparam>
public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>>
where V : struct, IEquatable<V>
where W : struct, IComparable<W>, IEquatable<W>
{
}
}
``` |
0a96a065-bed6-48b9-9b4f-4184efa43402 | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json;
namespace Toggl.Phoebe.Data
{
public class ForeignKeyJsonConverter : JsonConverter
{
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
{
var model = (Model)value;
if (model == null) {
writer.WriteNull ();
return;
}
writer.WriteValue (model.RemoteId);
}
public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) {
return null;
}
var remoteId = Convert.ToInt64 (reader.Value);
var model = Model.Manager.GetByRemoteId (objectType, remoteId);
if (model == null) {
model = (Model)Activator.CreateInstance (objectType);
model.RemoteId = remoteId;
model = Model.Update (model);
}
return model;
}
public override bool CanConvert (Type objectType)
{
return objectType.IsSubclassOf (typeof(Model));
}
}
}
```
Fix temporary models for relations. | ```c#
using System;
using Newtonsoft.Json;
namespace Toggl.Phoebe.Data
{
public class ForeignKeyJsonConverter : JsonConverter
{
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
{
var model = (Model)value;
if (model == null) {
writer.WriteNull ();
return;
}
writer.WriteValue (model.RemoteId);
}
public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) {
return null;
}
var remoteId = Convert.ToInt64 (reader.Value);
var model = Model.Manager.GetByRemoteId (objectType, remoteId);
if (model == null) {
model = (Model)Activator.CreateInstance (objectType);
model.RemoteId = remoteId;
model.ModifiedAt = new DateTime ();
model = Model.Update (model);
}
return model;
}
public override bool CanConvert (Type objectType)
{
return objectType.IsSubclassOf (typeof(Model));
}
}
}
``` |
b030bce2-26df-43c1-a513-4f5b2f00ae6f | {
"language": "C#"
} | ```c#
using System;
using Android.App;
using Android.Content;
using Android.Support.V4.Content;
namespace Toggl.Joey.Net
{
[BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")]
[IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" },
Categories = new string[]{ "com.toggl.timer" })]
public class GcmBroadcastReceiver : WakefulBroadcastReceiver
{
public override void OnReceive (Context context, Intent intent)
{
var comp = new ComponentName (context,
Java.Lang.Class.FromType (typeof(GcmService)));
StartWakefulService (context, (intent.SetComponent (comp)));
ResultCode = Result.Ok;
}
}
}
```
Use new intent instead of reusing broadcast one. | ```c#
using System;
using Android.App;
using Android.Content;
using Android.Support.V4.Content;
namespace Toggl.Joey.Net
{
[BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")]
[IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" },
Categories = new string[]{ "com.toggl.timer" })]
public class GcmBroadcastReceiver : WakefulBroadcastReceiver
{
public override void OnReceive (Context context, Intent intent)
{
var serviceIntent = new Intent (context, typeof(GcmService));
serviceIntent.ReplaceExtras (intent.Extras);
StartWakefulService (context, serviceIntent);
ResultCode = Result.Ok;
}
}
}
``` |
de11a849-b4d4-4c2f-9dd3-158bc1473ef3 | {
"language": "C#"
} | ```c#
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MarkdownDeep;
using SIL.IO;
namespace SIL.Windows.Forms.ReleaseNotes
{
/// <summary>
/// Shows a dialog for release notes; accepts html and markdown
/// </summary>
public partial class ShowReleaseNotesDialog : Form
{
private readonly string _path;
private TempFile _temp;
private readonly Icon _icon;
public ShowReleaseNotesDialog(Icon icon, string path)
{
_path = path;
_icon = icon;
InitializeComponent();
}
private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
{
string contents = File.ReadAllText(_path);
var md = new Markdown();
_temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp
File.WriteAllText(_temp.Path, md.Transform(contents));
_browser.Url = new Uri(_temp.Path);
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// a bug in Mono requires us to wait to set Icon until handle created.
Icon = _icon;
}
}
}
```
Set character encoding when displaying html from markdown (BL-3785) | ```c#
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MarkdownDeep;
using SIL.IO;
namespace SIL.Windows.Forms.ReleaseNotes
{
/// <summary>
/// Shows a dialog for release notes; accepts html and markdown
/// </summary>
public partial class ShowReleaseNotesDialog : Form
{
private readonly string _path;
private TempFile _temp;
private readonly Icon _icon;
public ShowReleaseNotesDialog(Icon icon, string path)
{
_path = path;
_icon = icon;
InitializeComponent();
}
private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
{
string contents = File.ReadAllText(_path);
var md = new Markdown();
_temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp
File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents)));
_browser.Url = new Uri(_temp.Path);
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// a bug in Mono requires us to wait to set Icon until handle created.
Icon = _icon;
}
private string GetBasicHtmlFromMarkdown(string markdownHtml)
{
return string.Format("<html><head><meta charset=\"utf-8\"/></head><body>{0}</body></html>", markdownHtml);
}
}
}
``` |
3f4de645-f8eb-470c-904c-511beac95fd2 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace VasysRomanNumeralsKata
{
public class RomanNumeral
{
private int? _baseTenRepresentation = null;
public RomanNumeral(int baseTenNumber)
{
_baseTenRepresentation = baseTenNumber;
}
public string GenerateRomanNumeralRepresntation()
{
StringBuilder romanNumeralBuilder = new StringBuilder();
int numberOfThousands = (int)_baseTenRepresentation / 1000;
if (numberOfThousands > 0)
{
for(int i = 0; i < numberOfThousands; i++)
{
romanNumeralBuilder.Append("M");
}
}
int remainder = (int)_baseTenRepresentation % 1000;
if (remainder >= 900)
{
romanNumeralBuilder.Append("CM");
remainder -= 900;
}
if(remainder >= 500)
{
romanNumeralBuilder.Append("D");
remainder -= 500;
}
if (remainder >= 400)
{
romanNumeralBuilder.Append("CD");
remainder -= 400;
}
while(remainder >= 100)
{
romanNumeralBuilder.Append("C");
remainder -= 100;
}
int numberOfTens = remainder / 10;
if (numberOfTens > 0)
{
for (int i = 0; i < numberOfTens; i++)
{
romanNumeralBuilder.Append("X");
}
}
return romanNumeralBuilder.ToString();
}
}
}
```
Refactor logic for thousands (M, MM, MMM). | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace VasysRomanNumeralsKata
{
public class RomanNumeral
{
private int? _baseTenRepresentation = null;
public RomanNumeral(int baseTenNumber)
{
_baseTenRepresentation = baseTenNumber;
}
public string GenerateRomanNumeralRepresntation()
{
StringBuilder romanNumeralBuilder = new StringBuilder();
int remainder = (int)_baseTenRepresentation;
while(remainder / 1000 > 0)
{
romanNumeralBuilder.Append("M");
remainder -= 1000;
}
if (remainder >= 900)
{
romanNumeralBuilder.Append("CM");
remainder -= 900;
}
if(remainder >= 500)
{
romanNumeralBuilder.Append("D");
remainder -= 500;
}
if (remainder >= 400)
{
romanNumeralBuilder.Append("CD");
remainder -= 400;
}
while(remainder >= 100)
{
romanNumeralBuilder.Append("C");
remainder -= 100;
}
int numberOfTens = remainder / 10;
if (numberOfTens > 0)
{
for (int i = 0; i < numberOfTens; i++)
{
romanNumeralBuilder.Append("X");
}
}
return romanNumeralBuilder.ToString();
}
}
}
``` |
ccd58703-2ce4-4d44-90ad-093bbfc1b2a4 | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
namespace AssemblyInfo
{
class Program
{
static void Main(string[] args)
{
if (args != null && args.Length > 0)
{
Assembly asm = null;
var name = args[0];
try
{
if (name.Substring(name.Length - 4, 4) != ".dll")
name += ".dll";
asm = Assembly.LoadFrom(name);
}
catch
{
try
{
var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + name;
asm = Assembly.LoadFrom(path);
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
return;
}
}
var x = asm.GetName();
System.Console.WriteLine("CodeBase: {0}", x.CodeBase);
System.Console.WriteLine("ContentType: {0}", x.ContentType);
System.Console.WriteLine("CultureInfo: {0}", x.CultureInfo);
System.Console.WriteLine("CultureName: {0}", x.CultureName);
System.Console.WriteLine("FullName: {0}", x.FullName);
System.Console.WriteLine("Name: {0}", x.Name);
System.Console.WriteLine("Version: {0}", x.Version);
System.Console.WriteLine("VersionCompatibility: {0}", x.VersionCompatibility);
}
else
{
System.Console.WriteLine("Usage: asminfo.exe assembly");
}
}
}
}
```
Add braces for the 'if (name.Substring(... ' | ```c#
using System;
using System.Reflection;
namespace AssemblyInfo
{
class Program
{
static void Main(string[] args)
{
if (args != null && args.Length > 0)
{
Assembly asm = null;
var name = args[0];
try
{
if (name.Substring(name.Length - 4, 4) != ".dll")
{
name += ".dll";
}
asm = Assembly.LoadFrom(name);
}
catch
{
try
{
var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + name;
asm = Assembly.LoadFrom(path);
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
return;
}
}
var x = asm.GetName();
System.Console.WriteLine("CodeBase: {0}", x.CodeBase);
System.Console.WriteLine("ContentType: {0}", x.ContentType);
System.Console.WriteLine("CultureInfo: {0}", x.CultureInfo);
System.Console.WriteLine("CultureName: {0}", x.CultureName);
System.Console.WriteLine("FullName: {0}", x.FullName);
System.Console.WriteLine("Name: {0}", x.Name);
System.Console.WriteLine("Version: {0}", x.Version);
System.Console.WriteLine("VersionCompatibility: {0}", x.VersionCompatibility);
}
else
{
System.Console.WriteLine("Usage: asminfo.exe assembly");
}
}
}
}
``` |
479b5dea-b067-4242-bddd-aeca8c4962bc | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
// Adapted from
// https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/
namespace XlsxValidator
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Count() == 0)
{
Console.WriteLine("No document given");
return;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(args[0], false))
{
var validator = new OpenXmlValidator();
var errors = validator.Validate(doc);
if (errors.Count() == 0)
{
Console.WriteLine("Document is valid");
}
else
{
Console.WriteLine("Document is not valid");
}
Console.WriteLine();
foreach (var error in errors)
{
Console.WriteLine("Error description: {0}", error.Description);
Console.WriteLine("Content type of part with error: {0}", error.Part.ContentType);
Console.WriteLine("Location of error: {0}", error.Path.XPath);
Console.WriteLine();
}
}
}
}
}```
Print filename with each error | ```c#
using System;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
// Adapted from
// https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/
namespace XlsxValidator
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Count() == 0)
{
Console.WriteLine("No document given");
return;
}
var path = args[0];
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(path, false))
{
var validator = new OpenXmlValidator();
var errors = validator.Validate(doc);
if (errors.Count() == 0)
{
Console.WriteLine("Document is valid");
}
else
{
Console.WriteLine("Document is not valid");
}
Console.WriteLine();
foreach (var error in errors)
{
Console.WriteLine("File: {0}", path);
Console.WriteLine("Error: {0}", error.Description);
Console.WriteLine("ContentType: {0}", error.Part.ContentType);
Console.WriteLine("XPath: {0}", error.Path.XPath);
Console.WriteLine();
}
}
}
}
}``` |
72bc4185-5fb6-4336-bcf4-f03b4451d229 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Mvc;
using Xunit;
using DiceApi.WebApi.Controllers;
namespace DiceApi.WebApi.Tests
{
/// <summary>
/// Test class for <see cref="DieController" />.
/// </summary>
public class DieControllerTest
{
/// <summary>
/// Verifies that Get() returns a BadRequestResult when given an invalid number
/// of sides for the die to roll.
/// </summary>
[Fact]
public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult()
{
var sut = new DieController();
var result = sut.Get(-1);
Assert.Equal(typeof(BadRequestResult), result.GetType());
}
/// <summary>
/// Verifies that Get() returns an OkObjectResult when given an valid number
/// of sides for the die to roll.
/// </summary>
[Fact]
public void Get_GivenValidSizeValue_ReturnsOkResult()
{
var sut = new DieController();
var result = sut.Get(6);
Assert.Equal(typeof(OkObjectResult), result.GetType());
}
}
}
```
Add extra check on result type | ```c#
using Microsoft.AspNetCore.Mvc;
using Xunit;
using DiceApi.WebApi.Controllers;
namespace DiceApi.WebApi.Tests
{
/// <summary>
/// Test class for <see cref="DieController" />.
/// </summary>
public class DieControllerTest
{
/// <summary>
/// Verifies that Get() returns a BadRequestResult when given an invalid number
/// of sides for the die to roll.
/// </summary>
[Fact]
public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult()
{
var sut = new DieController();
var result = sut.Get(-1);
Assert.Equal(typeof(BadRequestResult), result.GetType());
}
/// <summary>
/// Verifies that Get() returns an OkObjectResult when given an valid number
/// of sides for the die to roll.
/// </summary>
[Fact]
public void Get_GivenValidSizeValue_ReturnsOkResult()
{
var sut = new DieController();
var result = sut.Get(6);
Assert.Equal(typeof(OkObjectResult), result.GetType());
Assert.Equal(typeof(int), ((OkObjectResult)result).Value.GetType());
}
}
}
``` |
5fcb361a-d528-4cc3-bdb7-cd2ef61b57da | {
"language": "C#"
} | ```c#
using System;
using Serilog;
using Serilog.Events;
using SerilogWeb.Classic;
namespace SerilogWeb.Test
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
ApplicationLifecycleModule.FormDataLoggingLevel = LogEventLevel.Debug;
ApplicationLifecycleModule.LogPostedFormData = LogPostedFormDataOption.OnMatch;
ApplicationLifecycleModule.ShouldLogPostedFormData = context => context.Response.StatusCode >= 400;
// ReSharper disable once PossibleNullReferenceException
ApplicationLifecycleModule.RequestFilter = context => context.Request.Url.PathAndQuery.StartsWith("/__browserLink");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" )
.CreateLogger();
}
}
}```
Update sample app to use newer config API | ```c#
using System;
using Serilog;
using Serilog.Events;
using SerilogWeb.Classic;
namespace SerilogWeb.Test
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// ReSharper disable once PossibleNullReferenceException
SerilogWebClassic.Configuration
.IgnoreRequestsMatching(ctx => ctx.Request.Url.PathAndQuery.StartsWith("/__browserLink"))
.EnableFormDataLogging(formData => formData
.AtLevel(LogEventLevel.Debug)
.OnMatch(ctx => ctx.Response.StatusCode >= 400));
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" )
.CreateLogger();
}
}
}``` |
76ede54a-4310-4160-a5f3-1e0b82208ef1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BrightstarDB.InternalTests
{
internal static class TestConfiguration
{
public static string DataLocation = "..\\..\\Data\\";
}
}
```
Fix path to internal test data location | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BrightstarDB.InternalTests
{
internal static class TestConfiguration
{
public static string DataLocation = "..\\..\\..\\Data\\";
}
}
``` |
893d0644-adeb-456a-820e-8de1238305f4 | {
"language": "C#"
} | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
/// <summary>
/// Event arguments to the IsBrowserInitializedChanged event handler.
/// </summary>
public class IsBrowserInitializedChangedEventArgs : EventArgs
{
public bool IsBrowserInitialized { get; private set; }
public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized)
{
IsBrowserInitialized = isBrowserInitialized;
}
}
};
/// <summary>
/// A delegate type used to listen to IsBrowserInitializedChanged events.
/// </summary>
public delegate void IsBrowserInitializedChangedEventHandler(object sender, IsBrowserInitializedChangedEventArgs args);
}
```
Fix cherry pick, spaces not tabs and remove unused delegate | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
/// <summary>
/// Event arguments to the IsBrowserInitializedChanged event handler.
/// </summary>
public class IsBrowserInitializedChangedEventArgs : EventArgs
{
public bool IsBrowserInitialized { get; private set; }
public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized)
{
IsBrowserInitialized = isBrowserInitialized;
}
}
}
``` |
ae5dba13-0128-46e0-b4be-cc662531c518 | {
"language": "C#"
} | ```c#
using Evolve.Migration;
using System.Collections.Generic;
using Evolve.Utilities;
using Evolve.Connection;
namespace Evolve.Metadata
{
public abstract class MetadataTable : IEvolveMetadata
{
protected IWrappedConnection _wrappedConnection;
public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection)
{
Schema = Check.NotNullOrEmpty(schema, nameof(schema));
TableName = Check.NotNullOrEmpty(schema, nameof(tableName));
_wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection));
}
public string Schema { get; private set; }
public string TableName { get; private set; }
public abstract void Lock();
public abstract bool CreateIfNotExists();
public void AddMigrationMetadata(MigrationScript migration, bool success)
{
CreateIfNotExists();
InternalAddMigrationMetadata(migration, success);
}
public IEnumerable<MigrationMetadata> GetAllMigrationMetadata()
{
CreateIfNotExists();
return InternalGetAllMigrationMetadata();
}
protected abstract bool IsExists();
protected abstract void Create();
protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success);
protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata();
}
}
```
Fix tableName not correctly saved | ```c#
using Evolve.Migration;
using System.Collections.Generic;
using Evolve.Utilities;
using Evolve.Connection;
namespace Evolve.Metadata
{
public abstract class MetadataTable : IEvolveMetadata
{
protected IWrappedConnection _wrappedConnection;
public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection)
{
Schema = Check.NotNullOrEmpty(schema, nameof(schema));
TableName = Check.NotNullOrEmpty(tableName, nameof(tableName));
_wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection));
}
public string Schema { get; private set; }
public string TableName { get; private set; }
public abstract void Lock();
public abstract bool CreateIfNotExists();
public void AddMigrationMetadata(MigrationScript migration, bool success)
{
CreateIfNotExists();
InternalAddMigrationMetadata(migration, success);
}
public IEnumerable<MigrationMetadata> GetAllMigrationMetadata()
{
CreateIfNotExists();
return InternalGetAllMigrationMetadata();
}
protected abstract bool IsExists();
protected abstract void Create();
protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success);
protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata();
}
}
``` |
bc206daa-6eb9-49ee-b394-33e51d3b9fcd | {
"language": "C#"
} | ```c#
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Runtime.InteropServices;
using PInvoke;
using Xunit;
using static PInvoke.Kernel32;
public partial class Kernel32Facts
{
[Fact]
public void GetTickCount_Nonzero()
{
uint result = GetTickCount();
Assert.NotEqual(0u, result);
}
[Fact]
public void GetTickCount64_Nonzero()
{
ulong result = GetTickCount64();
Assert.NotEqual(0ul, result);
}
[Fact]
public void SetLastError_ImpactsMarshalGetLastWin32Error()
{
SetLastError(2);
Assert.Equal(2, Marshal.GetLastWin32Error());
}
[Fact]
public unsafe void GetStartupInfo_Title()
{
var startupInfo = STARTUPINFO.Create();
GetStartupInfo(ref startupInfo);
Assert.NotNull(startupInfo.Title);
Assert.NotEqual(0, startupInfo.Title.Length);
}
}
```
Add tests for `kernel32!SetHandleInformation` and `kernel32!GetHandleInformation` | ```c#
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.Kernel32;
public partial class Kernel32Facts
{
[Fact]
public void GetTickCount_Nonzero()
{
uint result = GetTickCount();
Assert.NotEqual(0u, result);
}
[Fact]
public void GetTickCount64_Nonzero()
{
ulong result = GetTickCount64();
Assert.NotEqual(0ul, result);
}
[Fact]
public void SetLastError_ImpactsMarshalGetLastWin32Error()
{
SetLastError(2);
Assert.Equal(2, Marshal.GetLastWin32Error());
}
[Fact]
public unsafe void GetStartupInfo_Title()
{
var startupInfo = STARTUPINFO.Create();
GetStartupInfo(ref startupInfo);
Assert.NotNull(startupInfo.Title);
Assert.NotEqual(0, startupInfo.Title.Length);
}
[Fact]
public void GetHandleInformation_DoesNotThrow()
{
var manualResetEvent = new ManualResetEvent(false);
GetHandleInformation(manualResetEvent.SafeWaitHandle, out var lpdwFlags);
}
[Fact]
public void SetHandleInformation_DoesNotThrow()
{
var manualResetEvent = new ManualResetEvent(false);
SetHandleInformation(
manualResetEvent.SafeWaitHandle,
HandleFlags.HANDLE_FLAG_INHERIT | HandleFlags.HANDLE_FLAG_PROTECT_FROM_CLOSE,
HandleFlags.HANDLE_FLAG_NONE);
}
}
``` |
19c371cd-c886-4774-a8dd-805cbc9410df | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
using strange.extensions.context.impl;
using strange.extensions.context.api;
public class RootContext : MVCSContext, IRootContext
{
public RootContext(MonoBehaviour view) : base(view)
{
}
public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags)
{
}
protected override void mapBindings()
{
base.mapBindings();
GameObject managers = GameObject.Find("Managers");
injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext();
EventManager eventManager = managers.GetComponent<EventManager>();
injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext();
ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>();
injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext();
IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>();
injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext();
}
public void Inject(Object o)
{
injectionBinder.injector.Inject(o);
}
}
```
Add the Material Manager to the context for injection. | ```c#
using UnityEngine;
using System.Collections;
using strange.extensions.context.impl;
using strange.extensions.context.api;
public class RootContext : MVCSContext, IRootContext
{
public RootContext(MonoBehaviour view) : base(view)
{
}
public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags)
{
}
protected override void mapBindings()
{
base.mapBindings();
GameObject managers = GameObject.Find("Managers");
injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext();
EventManager eventManager = managers.GetComponent<EventManager>();
injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext();
IMaterialManager materialManager = managers.GetComponent<MaterialManager>();
injectionBinder.Bind<IMaterialManager>().ToValue(materialManager).ToSingleton().CrossContext();
ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>();
injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext();
IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>();
injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext();
}
public void Inject(Object o)
{
injectionBinder.injector.Inject(o);
}
}
``` |
7e2e2b35-edbd-41c2-9df3-044f11a0eae1 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Linq;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Rulesets;
using osu.Game.Scoring.Legacy;
namespace osu.Game.Scoring
{
public class LegacyDatabasedScore : Score
{
public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store)
{
ScoreInfo = score;
string replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.File.GetStoragePath();
if (replayFilename == null)
return;
using (var stream = store.GetStream(replayFilename))
Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay;
}
}
}
```
Fix crash when attempting to watch a replay when the storage file doesn't exist | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Linq;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Rulesets;
using osu.Game.Scoring.Legacy;
namespace osu.Game.Scoring
{
public class LegacyDatabasedScore : Score
{
public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store)
{
ScoreInfo = score;
string replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.File.GetStoragePath();
if (replayFilename == null)
return;
using (var stream = store.GetStream(replayFilename))
{
if (stream == null)
return;
Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay;
}
}
}
}
``` |
0d5f905e-683f-4ee6-a443-7a25bcd75eaf | {
"language": "C#"
} | ```c#
using System;
using System.Net;
using Arango.fastJSON;
namespace Arango.Client.Protocol
{
internal class Response
{
internal int StatusCode { get; set; }
internal WebHeaderCollection Headers { get; set; }
internal string Body { get; set; }
internal DataType DataType { get; set; }
internal object Data { get; set; }
internal Exception Exception { get; set; }
internal AEerror Error { get; set; }
internal void DeserializeBody()
{
if (string.IsNullOrEmpty(Body))
{
DataType = DataType.Null;
Data = null;
}
else
{
var trimmedBody = Body.Trim();
// body contains JSON array
if (trimmedBody[0] == '[')
{
DataType = DataType.List;
}
// body contains JSON object
else if (trimmedBody[0] == '{')
{
DataType = DataType.Document;
}
else
{
DataType = DataType.Primitive;
}
Data = JSON.Parse(trimmedBody);
}
}
}
}
```
Put body data type check into switch statement | ```c#
using System;
using System.Net;
using Arango.fastJSON;
namespace Arango.Client.Protocol
{
internal class Response
{
internal int StatusCode { get; set; }
internal WebHeaderCollection Headers { get; set; }
internal string Body { get; set; }
internal DataType DataType { get; set; }
internal object Data { get; set; }
internal Exception Exception { get; set; }
internal AEerror Error { get; set; }
internal void DeserializeBody()
{
if (string.IsNullOrEmpty(Body))
{
DataType = DataType.Null;
Data = null;
}
else
{
var trimmedBody = Body.Trim();
switch (trimmedBody[0])
{
// body contains JSON array
case '[':
DataType = DataType.List;
break;
// body contains JSON object
case '{':
DataType = DataType.Document;
break;
default:
DataType = DataType.Primitive;
break;
}
Data = JSON.Parse(trimmedBody);
}
}
}
}
``` |
55ee5e50-3d7e-432b-95e1-ea996799ca83 | {
"language": "C#"
} | ```c#
using AutoMapper;
using SnittListan.Models;
using SnittListan.ViewModels;
namespace SnittListan.Infrastructure
{
public class MatchProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Match, MatchViewModel>()
.ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToShortDateString()))
.ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore()))
.ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam)));
}
}
}```
Format date with user culture | ```c#
using System.Threading;
using AutoMapper;
using SnittListan.Models;
using SnittListan.ViewModels;
namespace SnittListan.Infrastructure
{
public class MatchProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Match, MatchViewModel>()
.ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern, Thread.CurrentThread.CurrentCulture)))
.ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore()))
.ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam)));
}
}
}``` |
26b814df-9a13-4057-a8bc-5d7940265b07 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null)
{
if (from == null)
throw new ArgumentException("Unexpected null argument", nameof(from));
if (to == null)
throw new ArgumentException("Unexpected null argument", nameof(to));
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = callOpcode ?? OpCodes.Call;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
}```
Revert back to old signature (transpilers get confused with multiple version); add opcode=Call | ```c#
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
if (from == null)
throw new ArgumentException("Unexpected null argument", nameof(from));
if (to == null)
throw new ArgumentException("Unexpected null argument", nameof(to));
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = OpCodes.Call;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
}``` |
7b9b1a5e-8ea7-49a1-b8d0-3c75e2855e38 | {
"language": "C#"
} | ```c#
// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Website
{
using System;
using Extensions;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
/// <summary>
/// A class representing the entry-point to the application. This class cannot be inherited.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// The exit code from the application.
/// </returns>
public static int Main(string[] args)
{
try
{
using (var host = BuildWebHost(args))
{
host.Run();
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unhandled exception: {ex}");
return -1;
}
}
private static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseKestrel((p) => p.AddServerHeader = false)
.UseAutofac()
.UseAzureAppServices()
.UseApplicationInsights()
.UseStartup<Startup>()
.CaptureStartupErrors(true)
.Build();
}
}
}
```
Convert Main to be async | ```c#
// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Website
{
using System;
using System.Threading.Tasks;
using Extensions;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
/// <summary>
/// A class representing the entry-point to the application. This class cannot be inherited.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// A <see cref="Task{TResult}"/> that returns the exit code from the application.
/// </returns>
public static async Task<int> Main(string[] args)
{
try
{
using (var host = BuildWebHost(args))
{
await host.RunAsync();
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unhandled exception: {ex}");
return -1;
}
}
private static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseKestrel((p) => p.AddServerHeader = false)
.UseAutofac()
.UseAzureAppServices()
.UseApplicationInsights()
.UseStartup<Startup>()
.CaptureStartupErrors(true)
.Build();
}
}
}
``` |
b474a6e5-a78a-4b88-ab4e-51173d4721f7 | {
"language": "C#"
} | ```c#
using System.Windows;
namespace MilitaryPlanner.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
//InitializeComponent();
}
}
}
```
Fix for saving window state while minimized on closing | ```c#
using System.Windows;
namespace MilitaryPlanner.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
//InitializeComponent();
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
// if window is minimized, restore to avoid opening minimized on next run
if(WindowState == System.Windows.WindowState.Minimized)
{
WindowState = System.Windows.WindowState.Normal;
}
}
}
}
``` |
ebe88026-e70b-4bb4-8b1c-6de3fd3d2f96 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>;
using Expr = AST.Expression;
namespace ParcelTest
{
[TestClass]
class PrecedenceTests
{
[TestMethod]
public void MultiplicationVsAdditionPrecedenceTest()
{
var mwb = MockWorkbook.standardMockWorkbook();
var e = mwb.envForSheet(1);
var f = "=2*3+1";
ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName);
Expr correct =
Expr.NewBinOpExpr(
"+",
Expr.NewBinOpExpr(
"*",
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)),
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0))
),
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0))
);
try
{
Expr ast = asto.Value;
Assert.AreEqual(correct, ast);
}
catch (NullReferenceException nre)
{
Assert.Fail("Parse error: " + nre.Message);
}
}
}
}
```
Make precedence test public to be discoverable by test runner. | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>;
using Expr = AST.Expression;
namespace ParcelTest
{
[TestClass]
public class PrecedenceTests
{
[TestMethod]
public void MultiplicationVsAdditionPrecedenceTest()
{
var mwb = MockWorkbook.standardMockWorkbook();
var e = mwb.envForSheet(1);
var f = "=2*3+1";
ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName);
Expr correct =
Expr.NewBinOpExpr(
"+",
Expr.NewBinOpExpr(
"*",
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)),
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0))
),
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0))
);
try
{
Expr ast = asto.Value;
Assert.AreEqual(correct, ast);
}
catch (NullReferenceException nre)
{
Assert.Fail("Parse error: " + nre.Message);
}
}
}
}
``` |
0d845f54-64a1-4856-aa1f-4c629a7d6b62 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))]
public interface IMatchAllQuery : IQuery
{
[JsonProperty(PropertyName = "boost")]
double? Boost { get; set; }
[JsonProperty(PropertyName = "norm_field")]
string NormField { get; set; }
}
public class MatchAllQuery : QueryBase, IMatchAllQuery
{
public double? Boost { get; set; }
public string NormField { get; set; }
bool IQuery.Conditionless => false;
protected override void WrapInContainer(IQueryContainer container)
{
container.MatchAllQuery = this;
}
}
public class MatchAllQueryDescriptor
: QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery>
, IMatchAllQuery
{
bool IQuery.Conditionless => false;
string IQuery.Name { get; set; }
double? IMatchAllQuery.Boost { get; set; }
string IMatchAllQuery.NormField { get; set; }
public MatchAllQueryDescriptor Boost(double? boost) => Assign(a => a.Boost = boost);
public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField);
}
}
```
Fix post filter test after boost/descriptor refactoring | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))]
public interface IMatchAllQuery : IQuery
{
[JsonProperty(PropertyName = "norm_field")]
string NormField { get; set; }
}
public class MatchAllQuery : QueryBase, IMatchAllQuery
{
public string NormField { get; set; }
bool IQuery.Conditionless => false;
protected override void WrapInContainer(IQueryContainer container)
{
container.MatchAllQuery = this;
}
}
public class MatchAllQueryDescriptor
: QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery>
, IMatchAllQuery
{
bool IQuery.Conditionless => false;
string IMatchAllQuery.NormField { get; set; }
public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField);
}
}
``` |
7b57c7cf-bb07-41d2-990e-703347b17248 | {
"language": "C#"
} | ```c#
using System;
using System.Text;
using ModIso8583.Parse;
using ModIso8583.Util;
using Xunit;
namespace ModIso8583.Test.Parse
{
public class TestEncoding
{
[Fact(Skip = "character encoding issue")]
public void WindowsToUtf8()
{
string data = "05ácido";
Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
if (OsUtil.IsLinux())
encoding = Encoding.Default;
sbyte[] buf = data.GetSbytes(encoding);
LlvarParseInfo parser = new LlvarParseInfo
{
Encoding = Encoding.Default
};
IsoValue field = parser.Parse(1, buf, 0, null);
Assert.Equal(field.Value, data.Substring(2));
parser.Encoding = encoding;
field = parser.Parse(1, buf, 0, null);
Assert.Equal(data.Substring(2), field.Value);
}
}
}```
Fix OS based character Encoding issue | ```c#
using System;
using System.Text;
using ModIso8583.Parse;
using ModIso8583.Util;
using Xunit;
namespace ModIso8583.Test.Parse
{
public class TestEncoding
{
[Fact]
public void WindowsToUtf8()
{
string data = "05ácido";
Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
if (OsUtil.IsLinux())
encoding = Encoding.UTF8;
sbyte[] buf = data.GetSbytes(encoding);
LlvarParseInfo parser = new LlvarParseInfo
{
Encoding = Encoding.Default
};
if (OsUtil.IsLinux())
parser.Encoding = Encoding.UTF8;
IsoValue field = parser.Parse(1, buf, 0, null);
Assert.Equal(field.Value, data.Substring(2));
parser.Encoding = encoding;
field = parser.Parse(1, buf, 0, null);
Assert.Equal(data.Substring(2), field.Value);
}
}
}``` |
beac2051-674d-4f70-8c98-dc675f161f07 | {
"language": "C#"
} | ```c#
using Abp.AspNetCore.Mvc.Controllers;
using Abp.IdentityFramework;
using Microsoft.AspNetCore.Identity;
namespace Repairis.Controllers
{
public abstract class RepairisControllerBase: AbpController
{
protected RepairisControllerBase()
{
LocalizationSourceName = RepairisConsts.LocalizationSourceName;
}
protected void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}```
Disable exception throwing when ModelState is not valid | ```c#
using Abp.AspNetCore.Mvc.Controllers;
using Abp.IdentityFramework;
using Abp.Runtime.Validation;
using Microsoft.AspNetCore.Identity;
namespace Repairis.Controllers
{
[DisableValidation]
public abstract class RepairisControllerBase: AbpController
{
protected RepairisControllerBase()
{
LocalizationSourceName = RepairisConsts.LocalizationSourceName;
}
protected void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}``` |
7604dfd4-8dd0-459e-8099-15e8221fdbf7 | {
"language": "C#"
} | ```c#
using ReactiveUI;
using Windows.UI.Xaml;
namespace Ets.Mobile.Pages.Main
{
public sealed partial class MainPage
{
partial void PartialInitialize()
{
// Ensure to hide the status bar
var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
statusBar.BackgroundOpacity = 0;
statusBar.HideAsync().GetResults();
// Grade Presenter
// NOTE: Do not remove this code, can't bind to the presenter's source
this.OneWayBind(ViewModel, x => x.GradesPresenter, x => x.Grade.DataContext);
// Handle the button visibility according to Pivot Context (SelectedIndex)
Loaded += (s, e) =>
{
MainPivot.SelectionChanged += (sender, e2) =>
{
RefreshToday.Visibility = Visibility.Collapsed;
RefreshGrade.Visibility = Visibility.Collapsed;
switch (MainPivot.SelectedIndex)
{
case (int)MainPivotItem.Today:
RefreshToday.Visibility = Visibility.Visible;
break;
case (int)MainPivotItem.Grade:
RefreshGrade.Visibility = Visibility.Visible;
break;
}
};
};
}
}
}```
Use ReactiveUI Events for Loaded and SelectionChanged | ```c#
using System;
using Windows.UI.Xaml;
using EventsMixin = Windows.UI.Xaml.Controls.EventsMixin;
namespace Ets.Mobile.Pages.Main
{
public sealed partial class MainPage
{
partial void PartialInitialize()
{
// Ensure to hide the status bar
var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
statusBar.BackgroundOpacity = 0;
statusBar.HideAsync().GetResults();
// Handle the button visibility according to Pivot Context (SelectedIndex)
this.Events().Loaded.Subscribe(e =>
{
EventsMixin.Events(MainPivot).SelectionChanged.Subscribe(e2 =>
{
RefreshToday.Visibility = Visibility.Collapsed;
RefreshGrade.Visibility = Visibility.Collapsed;
switch (MainPivot.SelectedIndex)
{
case (int)MainPivotItem.Today:
RefreshToday.Visibility = Visibility.Visible;
break;
case (int)MainPivotItem.Grade:
RefreshGrade.Visibility = Visibility.Visible;
break;
}
});
});
}
}
}``` |
24ac360d-7dc5-46a4-b0a5-c263e9f6f2c1 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
}
}```
Add GetTititleEstimate that accepts data from URI. | ```c#
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
{
// All the values in "query" are null or zero
// Do some stuff with query if there were anything to do
return new string[] { "This is a CORS request.", "That works from any origin." };
}
}
}
``` |
06a32507-4116-46e8-bdef-77c86769342f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Sandbox.Game.World;
using Torch.Managers.PatchManager;
using Torch.Mod;
using VRage.Game;
namespace Torch.Patches
{
[PatchShim]
internal class SessionDownloadPatch
{
internal static void Patch(PatchContext context)
{
context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic));
}
// ReSharper disable once InconsistentNaming
private static void SuffixGetWorld(ref MyObjectBuilder_World __result)
{
if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID))
__result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID));
}
}
}
```
Stop Equinox complaining about session download patch not being static | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Sandbox.Game.World;
using Torch.Managers.PatchManager;
using Torch.Mod;
using VRage.Game;
namespace Torch.Patches
{
[PatchShim]
internal static class SessionDownloadPatch
{
internal static void Patch(PatchContext context)
{
context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic));
}
// ReSharper disable once InconsistentNaming
private static void SuffixGetWorld(ref MyObjectBuilder_World __result)
{
if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID))
__result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID));
}
}
}
``` |
d7dfa0f8-4aba-4d3c-b003-d17358b82b32 | {
"language": "C#"
} | ```c#
namespace Colore.Tests
{
using System;
using NUnit.Framework;
[TestFixture]
public class ColoreExceptionTests
{
[Test]
public void ShouldSetMessage()
{
const string Expected = "Test message.";
Assert.AreEqual(Expected, new ColoreException("Test message."));
}
[Test]
public void ShouldSetInnerException()
{
var expected = new Exception("Expected.");
var actual = new ColoreException(null, new Exception("Expected.")).InnerException;
Assert.AreEqual(expected.GetType(), actual.GetType());
Assert.AreEqual(expected.Message, actual.Message);
}
}
}
```
Fix ColoreException test performing wrong comparison. | ```c#
namespace Colore.Tests
{
using System;
using NUnit.Framework;
[TestFixture]
public class ColoreExceptionTests
{
[Test]
public void ShouldSetMessage()
{
const string Expected = "Test message.";
Assert.AreEqual(Expected, new ColoreException("Test message.").Message);
}
[Test]
public void ShouldSetInnerException()
{
var expected = new Exception("Expected.");
var actual = new ColoreException(null, new Exception("Expected.")).InnerException;
Assert.AreEqual(expected.GetType(), actual.GetType());
Assert.AreEqual(expected.Message, actual.Message);
}
}
}
``` |
ae8b64c1-254d-4bb7-a918-2581c14f903e | {
"language": "C#"
} | ```c#
@model IEnumerable<Soldier>
<h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
<td>
@Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id })
@Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id })
</td>
</tr>
}
</tbody>
</table>```
Move details to first in list | ```c#
@model IEnumerable<Soldier>
<h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>
@Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
@Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
</td>
</tr>
}
</tbody>
</table>``` |
a14bc825-2d95-42df-8a21-29755c88c3b9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Faker
{
public static class NumberFaker
{
private static Random _random = new Random();
public static int Number()
{
return _random.Next();
}
public static int Number(int maxValue)
{
return _random.Next(maxValue);
}
public static int Number(int minValue, int maxValue)
{
return _random.Next(minValue, maxValue);
}
}
}
```
Add thread-safe random number instance | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Faker
{
public static class NumberFaker
{
private static readonly RNGCryptoServiceProvider Global = new RNGCryptoServiceProvider();
[ThreadStatic]
private static Random _local;
private static Random Local
{
get
{
Random inst = _local;
if (inst == null)
{
byte[] buffer = new byte[4];
Global.GetBytes(buffer);
_local = inst = new Random(
BitConverter.ToInt32(buffer, 0));
}
return inst;
}
}
public static int Number()
{
return Local.Next();
}
public static int Number(int maxValue)
{
return Local.Next(maxValue);
}
public static int Number(int minValue, int maxValue)
{
return Local.Next(minValue, maxValue);
}
}
}``` |
368ac604-6d37-4fc2-ba91-07ab07d59e06 | {
"language": "C#"
} | ```c#
@model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)>
<h4>Verifizierungen</h4>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.UserInfo.Username)
</th>
<th>
@Html.DisplayNameFor(model => model.Guild.Name)
</th>
</tr>
</thead>
<tbody>
@foreach(var (userInfo, guild) in Model) {
<tr>
<td>
@if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) {
<img class="gommehdnet-forum-avatar" src="@userInfo.AvatarUrl" alt="Avatar" />
}
</td>
<td>
<a href="@userInfo.UrlPath">@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.UrlPath : userInfo.Username)</a>
</td>
<td>
<a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a>
</td>
</tr>
}
</tbody>
</table>
</div>```
Use Url instead of UrlPath. | ```c#
@model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)>
<h4>Verifizierungen</h4>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.UserInfo.Username)
</th>
<th>
@Html.DisplayNameFor(model => model.Guild.Name)
</th>
</tr>
</thead>
<tbody>
@foreach(var (userInfo, guild) in Model) {
<tr>
<td>
@if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) {
<img class="gommehdnet-forum-avatar" src="@userInfo.AvatarUrl" alt="Avatar" />
}
</td>
<td>
<a href="@userInfo.Url">@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.Url : userInfo.Username)</a>
</td>
<td>
<a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a>
</td>
</tr>
}
</tbody>
</table>
</div>``` |
1a31bc68-2b69-4b70-bdd2-340e0bbc32b1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DomainCore;
using DomainCore.Interfaces;
namespace Application.Interfaces
{
/// <summary>
/// Primary application interface
/// </summary>
public interface IInventoryService
{
/* ReadModel */
// Get all
Task<IEnumerable<InventoryItemDto>> InventoryAsync();
// Get one
Task<InventoryItemDto> GetItemAsync(Guid id);
Task<IEnumerable<AInventoryItemEvent>> InventoryEventsAsync(Guid id);
/* Commands */
// Create Item
Task PostItemAsync(InventoryItemDto item);
// Update Full Item
Task PutItemAsync(InventoryItemDto item);
// Delete Item
Task DeleteItemAsync(Guid id);
// Edit Item
Task PatchItemCountAsync(Guid id, int count, string reason);
Task PatchItemNameAsync(Guid id, string name, string reason);
Task PatchItemNoteAsync(Guid id, string note, string reason);
// Increase Item count
Task IncreaseInventory(Guid id, uint amount, string reason);
// Decrease Item count
Task DecreaseInventory(Guid id, uint amount, string reason);
// Activate Item
Task ActivateItem(Guid id, string reason);
// Deactivate Item
Task DisableItem(Guid id, string reason);
}
}
```
Revert "Changed generic object to a system object" | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DomainCore;
namespace Application.Interfaces
{
public interface IInventoryService
{
/* ReadModel */
// Get all
Task<IEnumerable<InventoryItemDto>> InventoryAsync();
// Get one
Task<InventoryItemDto> GetItemAsync(Guid id);
Task<IEnumerable<InventoryItemEvent>> InventoryEventsAsync(Guid id);
/* Commands */
// Create Item
Task PostItemAsync(InventoryItemDto item);
// Update Full Item
Task PutItemAsync(InventoryItemDto item);
// Delete Item
Task DeleteItemAsync(Guid id);
// Edit Item
Task PatchItemCountAsync(Guid id, int count, string reason);
Task PatchItemNameAsync(Guid id, string name, string reason);
Task PatchItemNoteAsync(Guid id, string note, string reason);
// Increase Item count
Task IncreaseInventory(Guid id, uint amount, string reason);
// Decrease Item count
Task DecreaseInventory(Guid id, uint amount, string reason);
// Activate Item
Task ActivateItem(Guid id, string reason);
// Deactivate Item
Task DisableItem(Guid id, string reason);
}
}
``` |
c867b982-b41f-4980-a619-91ec28a3d476 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Objects.Get.Movies
{
using Basic;
using Newtonsoft.Json;
public class TraktMovieImages
{
[JsonProperty(PropertyName = "fanart")]
public TraktImageSet FanArt { get; set; }
[JsonProperty(PropertyName = "poster")]
public TraktImageSet Poster { get; set; }
[JsonProperty(PropertyName = "logo")]
public TraktImage Logo { get; set; }
[JsonProperty(PropertyName = "clearart")]
public TraktImage ClearArt { get; set; }
[JsonProperty(PropertyName = "banner")]
public TraktImage Banner { get; set; }
[JsonProperty(PropertyName = "thumb")]
public TraktImage Thumb { get; set; }
}
}
```
Add documentation for movie images. | ```c#
namespace TraktApiSharp.Objects.Get.Movies
{
using Basic;
using Newtonsoft.Json;
/// <summary>A collection of images and image sets for a Trakt movie.</summary>
public class TraktMovieImages
{
/// <summary>Gets or sets the fan art image set.</summary>
[JsonProperty(PropertyName = "fanart")]
public TraktImageSet FanArt { get; set; }
/// <summary>Gets or sets the poster image set.</summary>
[JsonProperty(PropertyName = "poster")]
public TraktImageSet Poster { get; set; }
/// <summary>Gets or sets the loge image.</summary>
[JsonProperty(PropertyName = "logo")]
public TraktImage Logo { get; set; }
/// <summary>Gets or sets the clear art image.</summary>
[JsonProperty(PropertyName = "clearart")]
public TraktImage ClearArt { get; set; }
/// <summary>Gets or sets the banner image.</summary>
[JsonProperty(PropertyName = "banner")]
public TraktImage Banner { get; set; }
/// <summary>Gets or sets the thumb image.</summary>
[JsonProperty(PropertyName = "thumb")]
public TraktImage Thumb { get; set; }
}
}
``` |
14d23fc0-4d17-49cf-b689-8d483e3d9900 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Models;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class SerializableExceptionTests
{
[Fact]
public void UtxoRefereeSerialization()
{
var message = "Foo Bar Buzz";
var innerMessage = "Inner Foo Bar Buzz";
string innerStackTrace = "";
Exception ex;
string stackTrace;
try
{
try
{
throw new OperationCanceledException(innerMessage);
}
catch (Exception inner)
{
innerStackTrace = inner.StackTrace;
throw new InvalidOperationException(message, inner);
}
}
catch (Exception x)
{
stackTrace = x.StackTrace;
ex = x;
}
var serializableException = ex.ToSerializableException();
var base64string = SerializableException.ToBase64String(serializableException);
var result = SerializableException.FromBase64String(base64string);
Assert.Equal(message, result.Message);
Assert.Equal(stackTrace, result.StackTrace);
Assert.Equal(typeof(InvalidOperationException).FullName, result.ExceptionType);
Assert.Equal(innerMessage, result.InnerException.Message);
Assert.Equal(innerStackTrace, result.InnerException.StackTrace);
Assert.Equal(typeof(OperationCanceledException).FullName, result.InnerException.ExceptionType);
}
}
}
```
Use var instead of string | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Models;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class SerializableExceptionTests
{
[Fact]
public void UtxoRefereeSerialization()
{
var message = "Foo Bar Buzz";
var innerMessage = "Inner Foo Bar Buzz";
var innerStackTrace = "";
Exception ex;
string stackTrace;
try
{
try
{
throw new OperationCanceledException(innerMessage);
}
catch (Exception inner)
{
innerStackTrace = inner.StackTrace;
throw new InvalidOperationException(message, inner);
}
}
catch (Exception x)
{
stackTrace = x.StackTrace;
ex = x;
}
var serializableException = ex.ToSerializableException();
var base64string = SerializableException.ToBase64String(serializableException);
var result = SerializableException.FromBase64String(base64string);
Assert.Equal(message, result.Message);
Assert.Equal(stackTrace, result.StackTrace);
Assert.Equal(typeof(InvalidOperationException).FullName, result.ExceptionType);
Assert.Equal(innerMessage, result.InnerException.Message);
Assert.Equal(innerStackTrace, result.InnerException.StackTrace);
Assert.Equal(typeof(OperationCanceledException).FullName, result.InnerException.ExceptionType);
}
}
}
``` |
969f8c26-1273-4b90-b7ca-4f391212e805 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Kudu.Core.SourceControl;
namespace Kudu.Core.Deployment {
public class DeploymentManager : IDeploymentManager {
private readonly IRepository _repository;
private readonly IDeployerFactory _deployerFactory;
public DeploymentManager(IRepositoryManager repositoryManager,
IDeployerFactory deployerFactory) {
_repository = repositoryManager.GetRepository();
_deployerFactory = deployerFactory;
}
public IEnumerable<DeployResult> GetResults() {
throw new NotImplementedException();
}
public DeployResult GetResult(string id) {
throw new NotImplementedException();
}
public void Deploy(string id) {
IDeployer deployer = _deployerFactory.CreateDeployer();
deployer.Deploy(id);
}
public void Deploy() {
var activeBranch = _repository.GetBranches().FirstOrDefault(b => b.Active);
string id = _repository.CurrentId;
if (activeBranch != null) {
_repository.Update(activeBranch.Name);
}
else {
_repository.Update(id);
}
Deploy(id);
}
}
}
```
Create the repository only when it's needed for deployment. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Kudu.Core.SourceControl;
namespace Kudu.Core.Deployment {
public class DeploymentManager : IDeploymentManager {
private readonly IRepositoryManager _repositoryManager;
private readonly IDeployerFactory _deployerFactory;
public DeploymentManager(IRepositoryManager repositoryManager,
IDeployerFactory deployerFactory) {
_repositoryManager = repositoryManager;
_deployerFactory = deployerFactory;
}
public IEnumerable<DeployResult> GetResults() {
throw new NotImplementedException();
}
public DeployResult GetResult(string id) {
throw new NotImplementedException();
}
public void Deploy(string id) {
IDeployer deployer = _deployerFactory.CreateDeployer();
deployer.Deploy(id);
}
public void Deploy() {
var repository = _repositoryManager.GetRepository();
if (repository == null) {
return;
}
var activeBranch = repository.GetBranches().FirstOrDefault(b => b.Active);
string id = repository.CurrentId;
if (activeBranch != null) {
repository.Update(activeBranch.Name);
}
else {
repository.Update(id);
}
Deploy(id);
}
}
}
``` |
24d0f749-a90a-4284-8871-dbe649f265ba | {
"language": "C#"
} | ```c#
using System.Collections.ObjectModel;
using CoCo.UI.Data;
namespace CoCo.UI.ViewModels
{
public class OptionViewModel : BaseViewModel
{
public OptionViewModel(Option option, IResetValuesProvider resetValuesProvider)
{
// TODO: it will invoke one event at invocation of clear and by one event per added item
// Write custom BulkObservableCollection to avoid so many events
Languages.Clear();
foreach (var language in option.Languages)
{
Languages.Add(new LanguageViewModel(language, resetValuesProvider));
}
}
public ObservableCollection<LanguageViewModel> Languages { get; } = new ObservableCollection<LanguageViewModel>();
private LanguageViewModel _selectedLanguage;
public LanguageViewModel SelectedLanguage
{
get
{
if (_selectedLanguage is null && Languages.Count > 0)
{
SelectedLanguage = Languages[0];
}
return _selectedLanguage;
}
set => SetProperty(ref _selectedLanguage, value);
}
public Option ExtractData()
{
var option = new Option();
foreach (var languageViewModel in Languages)
{
option.Languages.Add(languageViewModel.ExtractData());
}
return option;
}
}
}```
Sort languages by ascending order. | ```c#
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using CoCo.UI.Data;
namespace CoCo.UI.ViewModels
{
public class OptionViewModel : BaseViewModel
{
private readonly ObservableCollection<LanguageViewModel> _languages = new ObservableCollection<LanguageViewModel>();
public OptionViewModel(Option option, IResetValuesProvider resetValuesProvider)
{
// TODO: it will invoke one event at invocation of clear and by one event per added item
// Write custom BulkObservableCollection to avoid so many events
_languages.Clear();
foreach (var language in option.Languages)
{
_languages.Add(new LanguageViewModel(language, resetValuesProvider));
}
Languages = CollectionViewSource.GetDefaultView(_languages);
Languages.SortDescriptions.Add(new SortDescription(nameof(LanguageViewModel.Name), ListSortDirection.Ascending));
}
public ICollectionView Languages { get; }
private LanguageViewModel _selectedLanguage;
public LanguageViewModel SelectedLanguage
{
get
{
if (_selectedLanguage is null && Languages.MoveCurrentToFirst())
{
SelectedLanguage = (LanguageViewModel)Languages.CurrentItem;
}
return _selectedLanguage;
}
set => SetProperty(ref _selectedLanguage, value);
}
public Option ExtractData()
{
var option = new Option();
foreach (var languageViewModel in _languages)
{
option.Languages.Add(languageViewModel.ExtractData());
}
return option;
}
}
}``` |
443ae580-4c3c-434f-a4f2-a427e93c988f | {
"language": "C#"
} | ```c#
using osu.Framework.Allocation;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using System;
using System.Collections.Generic;
using osuTK;
namespace osu.Framework.Tests.Visual.Sprites
{
public class TestSceneTexturedTriangle : FrameworkTestScene
{
public TestSceneTexturedTriangle()
{
Add(new TexturedTriangle
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(300, 150)
});
}
private class TexturedTriangle : Triangle
{
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
Texture = textures.Get(@"sample-texture");
}
}
}
}
```
Add the licence header and remove unused usings | ```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.Shapes;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osuTK;
namespace osu.Framework.Tests.Visual.Sprites
{
public class TestSceneTexturedTriangle : FrameworkTestScene
{
public TestSceneTexturedTriangle()
{
Add(new TexturedTriangle
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(300, 150)
});
}
private class TexturedTriangle : Triangle
{
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
Texture = textures.Get(@"sample-texture");
}
}
}
}
``` |
f10df392-c125-46f8-bb99-4d7e93b3fd38 | {
"language": "C#"
} | ```c#
public sealed class AppVeyorSettings
{
public bool IsLocal { get; set; }
public bool IsRunningOnAppVeyor { get; set; }
public bool IsPullRequest { get; set; }
public bool IsDevelopBranch { get; set; }
public bool IsMasterBranch { get; set; }
public bool IsTaggedBuild { get; set; }
public bool IsMaintenanceBuild { get; set; }
public static AppVeyorSettings Initialize(ICakeContext context)
{
var buildSystem = context.BuildSystem();
var branchName = buildSystem.AppVeyor.Environment.Repository.Branch;
var commitMessage = buildSystem.AppVeyor.Environment.Repository.Commit.Message?.Trim();
var isMaintenanceBuild = commitMessage?.StartsWith("(build)", StringComparison.OrdinalIgnoreCase) ?? false;
return new AppVeyorSettings
{
IsLocal = buildSystem.IsLocalBuild,
IsRunningOnAppVeyor = buildSystem.AppVeyor.IsRunningOnAppVeyor,
IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest,
IsDevelopBranch = "develop".Equals(branchName, StringComparison.OrdinalIgnoreCase),
IsMasterBranch = "master".Equals(branchName, StringComparison.OrdinalIgnoreCase),
IsTaggedBuild = IsBuildTagged(buildSystem),
IsMaintenanceBuild = isMaintenanceBuild
};
}
public static bool IsBuildTagged(BuildSystem buildSystem)
{
return buildSystem.AppVeyor.Environment.Repository.Tag.IsTag
&& !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name);
}
}```
Allow skipping publish of package when fixing docs. | ```c#
public sealed class AppVeyorSettings
{
public bool IsLocal { get; set; }
public bool IsRunningOnAppVeyor { get; set; }
public bool IsPullRequest { get; set; }
public bool IsDevelopBranch { get; set; }
public bool IsMasterBranch { get; set; }
public bool IsTaggedBuild { get; set; }
public bool IsMaintenanceBuild { get; set; }
public static AppVeyorSettings Initialize(ICakeContext context)
{
var buildSystem = context.BuildSystem();
var branchName = buildSystem.AppVeyor.Environment.Repository.Branch;
var commitMessage = buildSystem.AppVeyor.Environment.Repository.Commit.Message?.Trim();
var isMaintenanceBuild = (commitMessage?.StartsWith("(build)", StringComparison.OrdinalIgnoreCase) ?? false) ||
(commitMessage?.StartsWith("(docs)", StringComparison.OrdinalIgnoreCase) ?? false);
return new AppVeyorSettings
{
IsLocal = buildSystem.IsLocalBuild,
IsRunningOnAppVeyor = buildSystem.AppVeyor.IsRunningOnAppVeyor,
IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest,
IsDevelopBranch = "develop".Equals(branchName, StringComparison.OrdinalIgnoreCase),
IsMasterBranch = "master".Equals(branchName, StringComparison.OrdinalIgnoreCase),
IsTaggedBuild = IsBuildTagged(buildSystem),
IsMaintenanceBuild = isMaintenanceBuild
};
}
public static bool IsBuildTagged(BuildSystem buildSystem)
{
return buildSystem.AppVeyor.Environment.Repository.Tag.IsTag
&& !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name);
}
}``` |
73640ac3-5a71-44d5-9351-9a4393f4b3fd | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Resources;
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("BindableApplicationBar")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Filip Skakun")]
[assembly: AssemblyProduct("BindableApplicationBar")]
[assembly: AssemblyCopyright("Copyright © Filip Skakun, 2011-2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d0df5e03-2f69-4d10-a40d-25afcbbb7e09")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
```
Increase the version to 1.1.1. | ```c#
using System.Reflection;
using System.Resources;
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("BindableApplicationBar")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Filip Skakun")]
[assembly: AssemblyProduct("BindableApplicationBar")]
[assembly: AssemblyCopyright("Copyright © Filip Skakun, 2011-2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d0df5e03-2f69-4d10-a40d-25afcbbb7e09")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.1.1")]
[assembly: AssemblyFileVersion("1.1.1")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
``` |
ff2c947e-e9a1-4ccf-bd0b-4e38ba0a8254 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReleaseManager
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length == 0)
{
return;
}
var mainFileName = args[0];
var version = FileVersionInfo.GetVersionInfo(mainFileName).FileVersion;
var archive = ZipFile.Open("Release_" + version + ".zip", ZipArchiveMode.Create);
archive.CreateEntryFromFile(mainFileName, mainFileName);
for (int i = 1; i < args.Length; i++)
{
archive.CreateEntryFromFile(args[i], args[i]);
}
archive.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Environment.Exit(1);
}
}
}
}
```
Change release manager zip file name | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReleaseManager
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length == 0)
{
return;
}
var mainFileName = args[0];
var version = FileVersionInfo.GetVersionInfo(mainFileName).FileVersion;
var archive = ZipFile.Open(version + ".zip", ZipArchiveMode.Create);
archive.CreateEntryFromFile(mainFileName, mainFileName);
for (int i = 1; i < args.Length; i++)
{
archive.CreateEntryFromFile(args[i], args[i]);
}
archive.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Environment.Exit(1);
}
}
}
}
``` |
19eb7d5b-9588-47d8-871c-0377b43c51fb | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Screens;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack.
/// </summary>
public class ScreenBreadcrumbControl : BreadcrumbControl<Screen>
{
private Screen last;
public ScreenBreadcrumbControl(Screen initialScreen)
{
Current.ValueChanged += newScreen =>
{
if (last != newScreen && !newScreen.IsCurrentScreen)
newScreen.MakeCurrent();
};
onPushed(initialScreen);
}
private void screenChanged(Screen newScreen)
{
if (last != null)
{
last.Exited -= screenChanged;
last.ModePushed -= onPushed;
}
last = newScreen;
newScreen.Exited += screenChanged;
newScreen.ModePushed += onPushed;
Current.Value = newScreen;
}
private void onPushed(Screen screen)
{
Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem);
AddItem(screen);
screenChanged(screen);
}
}
}
```
Fix nullref when exiting the last screen. | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Screens;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack.
/// </summary>
public class ScreenBreadcrumbControl : BreadcrumbControl<Screen>
{
private Screen last;
public ScreenBreadcrumbControl(Screen initialScreen)
{
Current.ValueChanged += newScreen =>
{
if (last != newScreen && !newScreen.IsCurrentScreen)
newScreen.MakeCurrent();
};
onPushed(initialScreen);
}
private void screenChanged(Screen newScreen)
{
if (newScreen == null) return;
if (last != null)
{
last.Exited -= screenChanged;
last.ModePushed -= onPushed;
}
last = newScreen;
newScreen.Exited += screenChanged;
newScreen.ModePushed += onPushed;
Current.Value = newScreen;
}
private void onPushed(Screen screen)
{
Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem);
AddItem(screen);
screenChanged(screen);
}
}
}
``` |
7ebe2033-ac59-4683-9b46-608573dcbdd4 | {
"language": "C#"
} | ```c#
using System;
using R7.University.Core.Templates;
namespace R7.University.Core.Tests
{
class Program
{
static void Main (string [] args)
{
Console.WriteLine ("Please enter test number and press [Enter]:");
Console.WriteLine ("1. Workbook to CSV");
Console.WriteLine ("2. Workbook to linear CSV");
Console.WriteLine ("0. Exit");
if (int.TryParse (Console.ReadLine (), out int testNum)) {
switch (testNum) {
case 1: WorkbookToCsv (); break;
case 2: WorkbookToLinearCsv (); break;
}
}
}
static void WorkbookToCsv ()
{
var workbookManager = new WorkbookManager ();
Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.CSV));
}
static void WorkbookToLinearCsv ()
{
var workbookManager = new WorkbookManager ();
Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.LinearCSV));
}
}
}
```
Improve console menu for "visual" tests | ```c#
using System;
using R7.University.Core.Templates;
namespace R7.University.Core.Tests
{
class Program
{
static void Main (string [] args)
{
while (true) {
Console.WriteLine ("> Please enter test number and press [Enter]:");
Console.WriteLine ("---");
Console.WriteLine ("1. Workbook to CSV");
Console.WriteLine ("2. Workbook to linear CSV");
Console.WriteLine ("0. Exit");
if (int.TryParse (Console.ReadLine (), out int testNum)) {
switch (testNum) {
case 1: WorkbookToCsv (); break;
case 2: WorkbookToLinearCsv (); break;
case 0: return;
}
Console.WriteLine ("> Press any key to continue...");
Console.ReadKey ();
Console.WriteLine ();
}
}
}
static void WorkbookToCsv ()
{
Console.WriteLine ("--- Start test output");
var workbookManager = new WorkbookManager ();
Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.CSV));
Console.WriteLine ("--- End test output");
}
static void WorkbookToLinearCsv ()
{
Console.WriteLine ("--- Start test output");
var workbookManager = new WorkbookManager ();
Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.LinearCSV));
Console.WriteLine ("--- End test output");
}
}
}
``` |
8f2fc616-8591-4a1b-944e-3d509d0d3b62 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using ActiproSoftware.Text.Implementation;
namespace NQueryViewerActiproWpf
{
[Export(typeof(ILanguageServiceRegistrar))]
internal sealed class ComposableLanguageServiceRegistrar : ILanguageServiceRegistrar
{
[ImportMany]
public IEnumerable<Lazy<object, ILanguageServiceMetadata>> LanguageServices { get; set; }
public void RegisterServices(SyntaxLanguage syntaxLanguage)
{
foreach (var languageService in LanguageServices)
{
var type = languageService.Metadata.ServiceType;
syntaxLanguage.RegisterService(type, languageService.Value);
}
}
}
}```
Introduce variable to make code more readable | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using ActiproSoftware.Text.Implementation;
namespace NQueryViewerActiproWpf
{
[Export(typeof(ILanguageServiceRegistrar))]
internal sealed class ComposableLanguageServiceRegistrar : ILanguageServiceRegistrar
{
[ImportMany]
public IEnumerable<Lazy<object, ILanguageServiceMetadata>> LanguageServices { get; set; }
public void RegisterServices(SyntaxLanguage syntaxLanguage)
{
foreach (var languageService in LanguageServices)
{
var serviceType = languageService.Metadata.ServiceType;
var service = languageService.Value;
syntaxLanguage.RegisterService(serviceType, service);
}
}
}
}``` |
27465607-20ce-459b-a876-a5cf706a788b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LRU.Net
{
public class LruCache<TKey, TValue>
{
private readonly int _maxObjects;
private OrderedDictionary _data;
public LruCache(int maxObjects = 1000)
{
_maxObjects = maxObjects;
_data = new OrderedDictionary();
}
public void Add(TKey key, TValue value)
{
if (_data.Count >= _maxObjects)
{
_data.RemoveAt(0);
}
_data.Add(key, value);
}
public TValue Get(TKey key)
{
if (!_data.Contains(key)) throw new Exception();
var result = _data[key];
if (result == null) throw new Exception();
_data.Remove(key);
_data.Add(key, result);
return (TValue)result;
}
public bool Contains(TKey key)
{
return _data.Contains(key);
}
public TValue this[TKey key]
{
get { return Get(key); }
set { Add(key, value); }
}
}
}
```
Format code like a civilized man | ```c#
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LRU.Net
{
public class LruCache<TKey, TValue>
{
private readonly int _maxObjects;
private OrderedDictionary _data;
public LruCache(int maxObjects = 1000)
{
_maxObjects = maxObjects;
_data = new OrderedDictionary();
}
public void Add(TKey key, TValue value)
{
if (_data.Count >= _maxObjects)
{
_data.RemoveAt(0);
}
_data.Add(key, value);
}
public TValue Get(TKey key)
{
if (!_data.Contains(key))
{
throw new Exception($"Could not find item with key {key}");
}
var result = _data[key];
_data.Remove(key);
_data.Add(key, result);
return (TValue)result;
}
public bool Contains(TKey key)
{
return _data.Contains(key);
}
public TValue this[TKey key]
{
get { return Get(key); }
set { Add(key, value); }
}
}
}
``` |
61c7fd0e-033a-430b-9664-819a49b4111f | {
"language": "C#"
} | ```c#
namespace Nubot.Core.Nancy
{
using System.Linq;
using Abstractions;
using global::Nancy;
using global::Nancy.Conventions;
using global::Nancy.TinyIoc;
public class Bootstrapper : DefaultNancyBootstrapper
{
private readonly IRobot _robot;
public Bootstrapper(IRobot robot)
{
_robot = robot;
}
/// <summary>
/// Configures the container using AutoRegister followed by registration
/// of default INancyModuleCatalog and IRouteResolver.
/// </summary>
/// <param name="container">Container instance</param>
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
container.Register(_robot);
}
protected override void ConfigureConventions(NancyConventions nancyConventions)
{
base.ConfigureConventions(nancyConventions);
foreach (var staticPath in _robot.RobotPlugins.OfType<HttpPluginBase>().SelectMany(httpPlugin => httpPlugin.StaticPaths))
{
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(staticPath.Item1, staticPath.Item2));
}
nancyConventions.ViewLocationConventions.Add((viewName, model, viewLocationContext) => string.Concat("plugins/", viewLocationContext.ModulePath, "/Views/", viewName));
}
}
}```
Fix path building for plugins views | ```c#
namespace Nubot.Core.Nancy
{
using System.Linq;
using Abstractions;
using global::Nancy;
using global::Nancy.Conventions;
using global::Nancy.TinyIoc;
public class Bootstrapper : DefaultNancyBootstrapper
{
private readonly IRobot _robot;
public Bootstrapper(IRobot robot)
{
_robot = robot;
}
/// <summary>
/// Configures the container using AutoRegister followed by registration
/// of default INancyModuleCatalog and IRouteResolver.
/// </summary>
/// <param name="container">Container instance</param>
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
container.Register(_robot);
}
protected override void ConfigureConventions(NancyConventions nancyConventions)
{
base.ConfigureConventions(nancyConventions);
var httpPluginsStaticPaths = _robot.RobotPlugins.OfType<HttpPluginBase>().SelectMany(httpPlugin => httpPlugin.StaticPaths);
foreach (var staticPath in httpPluginsStaticPaths)
{
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(staticPath.Item1, staticPath.Item2));
}
nancyConventions.ViewLocationConventions.Add((viewName, model, viewLocationContext) => string.Concat("plugins", viewLocationContext.ModulePath, "/Views/", viewName));
}
}
}``` |
761269d9-84bd-480c-bc49-08efa56da2dc | {
"language": "C#"
} | ```c#
private async Task SendAsync(IAudioClient client, string path)
{
// Create FFmpeg using the previous example
var ffmpeg = CreateStream(path);
var output = ffmpeg.StandardOutput.BaseStream;
var discord = client.CreatePCMStream(AudioApplication.Mixed, 1920);
await output.CopyToAsync(discord);
await discord.FlushAsync();
}
```
Remove wrong parameter from FFMPEG audio example | ```c#
private async Task SendAsync(IAudioClient client, string path)
{
// Create FFmpeg using the previous example
var ffmpeg = CreateStream(path);
var output = ffmpeg.StandardOutput.BaseStream;
var discord = client.CreatePCMStream(AudioApplication.Mixed);
await output.CopyToAsync(discord);
await discord.FlushAsync();
}
``` |
ef057a45-f19a-4d18-9b52-c3a74049de8f | {
"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.Generic;
using JetBrains.Annotations;
namespace osu.Game.Skinning
{
/// <summary>
/// Provides access to skinnable elements.
/// </summary>
public interface ISkinSource : ISkin
{
event Action SourceChanged;
/// <summary>
/// Find the first (if any) skin that can fulfill the lookup.
/// This should be used for cases where subsequent lookups (for related components) need to occur on the same skin.
/// </summary>
/// <returns>The skin to be used for subsequent lookups, or <c>null</c> if none is available.</returns>
[CanBeNull]
ISkin FindProvider(Func<ISkin, bool> lookupFunction);
/// <summary>
/// Retrieve all sources available for lookup, with highest priority source first.
/// </summary>
IEnumerable<ISkin> AllSources { get; }
}
}
```
Add missing documentation for `SourceChanged` | ```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.Generic;
using JetBrains.Annotations;
namespace osu.Game.Skinning
{
/// <summary>
/// Provides access to skinnable elements.
/// </summary>
public interface ISkinSource : ISkin
{
/// <summary>
/// Fired whenever a source change occurs, signalling that consumers should re-query as required.
/// </summary>
event Action SourceChanged;
/// <summary>
/// Find the first (if any) skin that can fulfill the lookup.
/// This should be used for cases where subsequent lookups (for related components) need to occur on the same skin.
/// </summary>
/// <returns>The skin to be used for subsequent lookups, or <c>null</c> if none is available.</returns>
[CanBeNull]
ISkin FindProvider(Func<ISkin, bool> lookupFunction);
/// <summary>
/// Retrieve all sources available for lookup, with highest priority source first.
/// </summary>
IEnumerable<ISkin> AllSources { get; }
}
}
``` |
89175a40-0454-42ed-bb51-4b6df1194a1c | {
"language": "C#"
} | ```c#
using System;
using NugetCracker.Persistence;
namespace NugetCracker
{
class Program
{
private static MetaProjectPersistence _metaProjectPersistence;
static void Main(string[] args)
{
Console.WriteLine("NugetCracker 0.1\nSee https://github.com/monoman/NugetCracker\n");
_metaProjectPersistence = new MetaProjectPersistence(args.GetMetaProjectFilePath());
Console.WriteLine("Using {0}", _metaProjectPersistence.FilePath);
Console.WriteLine("Will be scanning directories:");
foreach (string dir in _metaProjectPersistence.ListOfDirectories)
Console.WriteLine("-- '{0}' > '{1}'", dir, _metaProjectPersistence.ToAbsolutePath(dir));
}
}
}
```
Use assembly version from NugetCracker assembly to print headline | ```c#
using System;
using NugetCracker.Persistence;
namespace NugetCracker
{
class Program
{
private static MetaProjectPersistence _metaProjectPersistence;
static Version Version
{
get {
return new System.Reflection.AssemblyName(System.Reflection.Assembly.GetCallingAssembly().FullName).Version;
}
}
static void Main(string[] args)
{
Console.WriteLine("NugetCracker {0}\nSee https://github.com/monoman/NugetCracker\n", Version.ToString(2));
_metaProjectPersistence = new MetaProjectPersistence(args.GetMetaProjectFilePath());
Console.WriteLine("Using {0}", _metaProjectPersistence.FilePath);
Console.WriteLine("Will be scanning directories:");
foreach (string dir in _metaProjectPersistence.ListOfDirectories)
Console.WriteLine("-- '{0}' > '{1}'", dir, _metaProjectPersistence.ToAbsolutePath(dir));
Console.WriteLine("Done!");
}
}
}
``` |
7feb5b04-a71b-484e-9968-3f78f38061b8 | {
"language": "C#"
} | ```c#
using System.Net.Http;
using Microsoft.Practices.Unity;
using Moq;
using MyGetConnector.Repositories;
namespace MyGetConnector.Tests
{
public static class TestUnityConfig
{
public static IUnityContainer GetMockedContainer()
{
var container = new UnityContainer();
container.RegisterInstance(new HttpClient());
container.RegisterInstance(typeof(ITriggerRepository), new Mock<ITriggerRepository>(MockBehavior.Strict).Object);
return container;
}
}
}
```
Remove unnecessary HttpClient registration in Unity | ```c#
using System.Net.Http;
using Microsoft.Practices.Unity;
using Moq;
using MyGetConnector.Repositories;
namespace MyGetConnector.Tests
{
public static class TestUnityConfig
{
public static IUnityContainer GetMockedContainer()
{
var container = new UnityContainer();
container.RegisterInstance(typeof(ITriggerRepository), new Mock<ITriggerRepository>(MockBehavior.Strict).Object);
return container;
}
}
}
``` |
d85bd0b3-c843-4b11-8d11-7544b12bcb08 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Concurrent;
using RabbitMQ.Client;
namespace Elders.Cronus.Transport.RabbitMQ
{
public class PublisherChannelResolver
{
private readonly ConcurrentDictionary<string, IModel> channelPerBoundedContext;
private readonly ConnectionResolver connectionResolver;
private static readonly object @lock = new object();
public PublisherChannelResolver(ConnectionResolver connectionResolver)
{
channelPerBoundedContext = new ConcurrentDictionary<string, IModel>();
this.connectionResolver = connectionResolver;
}
public IModel Resolve(string boundedContext, IRabbitMqOptions options)
{
IModel channel = GetExistingChannel(boundedContext);
if (channel is null || channel.IsClosed)
{
lock (@lock)
{
channel = GetExistingChannel(boundedContext);
if (channel is null || channel.IsClosed)
{
var connection = connectionResolver.Resolve(boundedContext, options);
channel = connection.CreateModel();
channel.ConfirmSelect();
if (channelPerBoundedContext.TryAdd(boundedContext, channel) == false)
{
throw new Exception("Kak go napravi tova?");
}
}
}
}
return channel;
}
private IModel GetExistingChannel(string boundedContext)
{
channelPerBoundedContext.TryGetValue(boundedContext, out IModel channel);
return channel;
}
}
}
```
Fix already closed connection and 'kak go napravi tova' exception | ```c#
using System.Collections.Generic;
using RabbitMQ.Client;
namespace Elders.Cronus.Transport.RabbitMQ
{
public class PublisherChannelResolver
{
private readonly Dictionary<string, IModel> channelPerBoundedContext;
private readonly ConnectionResolver connectionResolver;
private static readonly object @lock = new object();
public PublisherChannelResolver(ConnectionResolver connectionResolver)
{
channelPerBoundedContext = new Dictionary<string, IModel>();
this.connectionResolver = connectionResolver;
}
public IModel Resolve(string boundedContext, IRabbitMqOptions options)
{
IModel channel = GetExistingChannel(boundedContext);
if (channel is null || channel.IsClosed)
{
lock (@lock)
{
channel = GetExistingChannel(boundedContext);
if (channel?.IsClosed == true)
{
channelPerBoundedContext.Remove(boundedContext);
}
if (channel is null)
{
var connection = connectionResolver.Resolve(boundedContext, options);
IModel scopedChannel = connection.CreateModel();
scopedChannel.ConfirmSelect();
channelPerBoundedContext.Add(boundedContext, scopedChannel);
}
}
}
return GetExistingChannel(boundedContext);
}
private IModel GetExistingChannel(string boundedContext)
{
channelPerBoundedContext.TryGetValue(boundedContext, out IModel channel);
return channel;
}
}
}
``` |
76cf6395-8d54-41dd-b85f-a20ada9ffb8b | {
"language": "C#"
} | ```c#
using System.Buffers;
using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using GitVersion.Extensions;
namespace GitVersion.OutputVariables;
public class VersionVariablesJsonNumberConverter : JsonConverter<string>
{
public override bool CanConvert(Type typeToConvert)
=> typeToConvert == typeof(string);
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.Number && typeToConvert == typeof(string))
return reader.GetString() ?? "";
var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed)
return number.ToString();
var data = reader.GetString();
throw new InvalidOperationException($"'{data}' is not a correct expected value!")
{
Source = nameof(VersionVariablesJsonNumberConverter)
};
}
public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
{
if (value.IsNullOrWhiteSpace())
{
writer.WriteNullValue();
}
else if (int.TryParse(value, out var number))
{
writer.WriteNumberValue(number);
}
else
{
throw new InvalidOperationException($"'{value}' is not a correct expected value!")
{
Source = nameof(VersionVariablesJsonStringConverter)
};
}
}
public override bool HandleNull => true;
}
```
Handle long values when writing version variables | ```c#
using System.Buffers;
using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using GitVersion.Extensions;
namespace GitVersion.OutputVariables;
public class VersionVariablesJsonNumberConverter : JsonConverter<string>
{
public override bool CanConvert(Type typeToConvert)
=> typeToConvert == typeof(string);
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.Number && typeToConvert == typeof(string))
return reader.GetString() ?? "";
var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed)
return number.ToString();
var data = reader.GetString();
throw new InvalidOperationException($"'{data}' is not a correct expected value!")
{
Source = nameof(VersionVariablesJsonNumberConverter)
};
}
public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
{
if (value.IsNullOrWhiteSpace())
{
writer.WriteNullValue();
}
else if (long.TryParse(value, out var number))
{
writer.WriteNumberValue(number);
}
else
{
throw new InvalidOperationException($"'{value}' is not a correct expected value!")
{
Source = nameof(VersionVariablesJsonStringConverter)
};
}
}
public override bool HandleNull => true;
}
``` |
73316cbd-832a-4c5b-961e-74cb62f948ff | {
"language": "C#"
} | ```c#
using System.IO;
using NUnit.Framework;
namespace XeroApi.Tests
{
public class MimeTypesTests
{
[Test]
public void it_can_return_the_mime_type_for_a_filename()
{
string mimeType = MimeTypes.GetMimeType("anyFilename.pdf");
Assert.AreEqual("application/pdf", mimeType);
}
[Test]
public void it_can_return_the_mime_type_for_a_filepath()
{
string mimeType = MimeTypes.GetMimeType(@"c:\any\dir\anyFilename.jpeg");
Assert.AreEqual("image/jpeg", mimeType);
}
[Test]
public void it_can_return_the_mime_type_for_a_fileinfo()
{
var mimeType = MimeTypes.GetMimeType(new FileInfo("anyFilename.docx"));
Assert.AreEqual("application/vnd.openxmlformats-officedocument.wordprocessingml.document", mimeType);
}
}
}
```
Fix tests that don't work on the build server (apparently .pdf and .docx file extentions are not recognised by Windows out of the box) | ```c#
using System.IO;
using NUnit.Framework;
namespace XeroApi.Tests
{
public class MimeTypesTests
{
[Test]
public void it_can_return_the_mime_type_for_a_filename()
{
string mimeType = MimeTypes.GetMimeType("anyFilename.png");
Assert.AreEqual("image/png", mimeType);
}
[Test]
public void it_can_return_the_mime_type_for_a_filepath()
{
string mimeType = MimeTypes.GetMimeType(@"c:\any\dir\anyFilename.jpeg");
Assert.AreEqual("image/jpeg", mimeType);
}
[Test]
public void it_can_return_the_mime_type_for_a_fileinfo()
{
var mimeType = MimeTypes.GetMimeType(new FileInfo("anyFilename.txt"));
Assert.AreEqual("text/plain", mimeType);
}
}
}
``` |
42196484-b389-4396-8eda-e7f1dd715200 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using DataAccessExamples.Core.Data;
using DataAccessExamples.Core.ViewModels;
namespace DataAccessExamples.Core.Services
{
public class LazyOrmDepartmentService : IDepartmentService
{
private readonly EmployeesContext context;
public LazyOrmDepartmentService(EmployeesContext context)
{
this.context = context;
}
public DepartmentList ListDepartments()
{
return new DepartmentList {
Departments = context.Departments.OrderBy(d => d.Code).Select(d => new DepartmentSummary
{
Code = d.Code,
Name = d.Name
})
};
}
public DepartmentList ListAverageSalaryPerDepartment()
{
return new DepartmentList
{
Departments = context.Departments.AsEnumerable().Select(d => new DepartmentSalary
{
Code = d.Code,
Name = d.Name,
AverageSalary =
(int) d.DepartmentEmployees.Select(
e => e.Employee.Salaries.LastOrDefault(s => s.ToDate > DateTime.Now))
.Where(s => s != null)
.Average(s => s.Amount)
})
};
}
}
}
```
Correct behaviour of Lazy ORM implementation | ```c#
using System;
using System.Linq;
using DataAccessExamples.Core.Data;
using DataAccessExamples.Core.ViewModels;
namespace DataAccessExamples.Core.Services
{
public class LazyOrmDepartmentService : IDepartmentService
{
private readonly EmployeesContext context;
public LazyOrmDepartmentService(EmployeesContext context)
{
this.context = context;
}
public DepartmentList ListDepartments()
{
return new DepartmentList {
Departments = context.Departments.OrderBy(d => d.Code).Select(d => new DepartmentSummary
{
Code = d.Code,
Name = d.Name
})
};
}
public DepartmentList ListAverageSalaryPerDepartment()
{
return new DepartmentList
{
Departments = context.Departments.AsEnumerable().Select(d => new DepartmentSalary
{
Code = d.Code,
Name = d.Name,
AverageSalary =
(int) d.DepartmentEmployees.Select(
e => e.Employee.Salaries.LastOrDefault(s => s.ToDate > DateTime.Now))
.Where(s => s != null)
.Average(s => s.Amount)
}).OrderByDescending(d => d.AverageSalary)
};
}
}
}
``` |
e4d1eb85-fe5b-4ff6-9dbe-1e5de3e517e1 | {
"language": "C#"
} | ```c#
using System;
using Mapsui.Layers;
using Mapsui.Providers;
using Mapsui.Styles;
using Mapsui.UI;
using Mapsui.Utilities;
namespace Mapsui.Samples.Common.Maps
{
public class RasterizingLayerSample : ISample
{
public string Name => "Rasterizing Layer";
public string Category => "Special";
public void Setup(IMapControl mapControl)
{
mapControl.Map = CreateMap();
}
public static Map CreateMap()
{
var map = new Map();
map.Layers.Add(OpenStreetMap.CreateTileLayer());
map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer()));
return map;
}
private static MemoryLayer CreateRandomPointLayer()
{
var rnd = new Random();
var features = new Features();
for (var i = 0; i < 100; i++)
{
var feature = new Feature
{
Geometry = new Geometries.Point(rnd.Next(0, 5000000), rnd.Next(0, 5000000))
};
features.Add(feature);
}
var provider = new MemoryProvider(features);
return new MemoryLayer
{
DataSource = provider,
Style = new SymbolStyle
{
SymbolType = SymbolType.Triangle,
Fill = new Brush(Color.Red)
}
};
}
}
}```
Add zoom into rasterlayer data in the sample | ```c#
using System;
using Mapsui.Layers;
using Mapsui.Providers;
using Mapsui.Styles;
using Mapsui.UI;
using Mapsui.Utilities;
namespace Mapsui.Samples.Common.Maps
{
public class RasterizingLayerSample : ISample
{
public string Name => "Rasterizing Layer";
public string Category => "Special";
public void Setup(IMapControl mapControl)
{
mapControl.Map = CreateMap();
}
public static Map CreateMap()
{
var map = new Map();
map.Layers.Add(OpenStreetMap.CreateTileLayer());
map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer()));
map.Home = n => n.NavigateTo(map.Layers[1].Envelope.Grow(map.Layers[1].Envelope.Width * 0.1));
return map;
}
private static MemoryLayer CreateRandomPointLayer()
{
var rnd = new Random(3462); // Fix the random seed so the features don't move after a refresh
var features = new Features();
for (var i = 0; i < 100; i++)
{
var feature = new Feature
{
Geometry = new Geometries.Point(rnd.Next(0, 5000000), rnd.Next(0, 5000000))
};
features.Add(feature);
}
var provider = new MemoryProvider(features);
return new MemoryLayer
{
DataSource = provider,
Style = new SymbolStyle
{
SymbolType = SymbolType.Triangle,
Fill = new Brush(Color.Red)
}
};
}
}
}``` |
9c2cef33-1a5a-41b7-a36a-65217353e9e7 | {
"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("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// 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.1.0.8")]
[assembly: AssemblyFileVersion("1.1.0.8")]
```
Increment version for new 'skip' querystring support | ```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("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// 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.1.0.9")]
[assembly: AssemblyFileVersion("1.1.0.9")]
``` |
59cc5522-a1f4-441d-a602-08241c830312 | {
"language": "C#"
} | ```c#
using System.IO;
namespace Leaf.Nodes
{
/// <summary>
/// Base class for all node types.
/// </summary>
public abstract class Node
{
/// <summary>
/// Writes the data of the node to a stream.
/// </summary>
/// <param name="writer">Writer to use for putting data in the stream.</param>
public abstract void Write(BinaryWriter writer);
}
}
```
Change access of Write() to internal | ```c#
using System.IO;
namespace Leaf.Nodes
{
/// <summary>
/// Base class for all node types.
/// </summary>
public abstract class Node
{
/// <summary>
/// Writes the data of the node to a stream.
/// </summary>
/// <param name="writer">Writer to use for putting data in the stream.</param>
internal abstract void Write(BinaryWriter writer);
}
}
``` |
aab51791-2539-4fc2-a5e1-5a124a7a9e72 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Nether.Data.Identity
{
public static class LoginProvider
{
public const string UserNamePassword = "password";
public const string FacebookUserAccessToken = "facebook-user-access-token";
}
}
```
Update fb-usertoken grant to reuser Facebook id | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Nether.Data.Identity
{
public static class LoginProvider
{
public const string UserNamePassword = "password";
public const string FacebookUserAccessToken = "Facebook"; // use the same identifier as the implicit flow for facebook
}
}
``` |
406af0fa-4fc8-4136-9004-7a1ed1ef2d28 | {
"language": "C#"
} | ```c#
using Glimpse;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace Glimpse
{
public class GlimpseServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Discovery & Reflection.
//
yield return describe.Transient<ITypeActivator, DefaultTypeActivator>();
yield return describe.Transient<ITypeSelector, DefaultTypeSelector>();
yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>();
yield return describe.Transient<ITypeService, DefaultTypeService>();
yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>));
//
// Messages.
//
yield return describe.Singleton<IMessageConverter, DefaultMessageConverter>();
//
// JSON.Net.
//
yield return describe.Singleton<JsonSerializer>(x => new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
}
}
}```
Add comment about how IDiscoverableCollection is treated | ```c#
using Glimpse;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace Glimpse
{
public class GlimpseServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Discovery & Reflection.
//
yield return describe.Transient<ITypeActivator, DefaultTypeActivator>();
yield return describe.Transient<ITypeSelector, DefaultTypeSelector>();
yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>();
yield return describe.Transient<ITypeService, DefaultTypeService>();
yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>));
// TODO: consider making above singleton
//
// Messages.
//
yield return describe.Singleton<IMessageConverter, DefaultMessageConverter>();
//
// JSON.Net.
//
yield return describe.Singleton<JsonSerializer>(x => new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
}
}
}``` |
66dc6807-a8e9-4032-af21-a1fed5557ec2 | {
"language": "C#"
} | ```c#
using Rareform.Validation;
using System.Collections.Generic;
using System.IO;
namespace Espera.Core.Management
{
public class LibraryFileWriter : ILibraryWriter
{
private readonly string targetPath;
public LibraryFileWriter(string targetPath)
{
if (targetPath == null)
Throw.ArgumentNullException(() => targetPath);
this.targetPath = targetPath;
}
public void Write(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath)
{
using (FileStream targetStream = File.Create(this.targetPath))
{
LibraryWriter.Write(songs, playlists, songSourcePath, targetStream);
}
}
}
}```
Create a temporary library file and rename it to reduce the chance of library corruption | ```c#
using Rareform.Validation;
using System;
using System.Collections.Generic;
using System.IO;
namespace Espera.Core.Management
{
public class LibraryFileWriter : ILibraryWriter
{
private readonly string targetPath;
public LibraryFileWriter(string targetPath)
{
if (targetPath == null)
Throw.ArgumentNullException(() => targetPath);
this.targetPath = targetPath;
}
public void Write(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath)
{
// Create a temporary file, write the library it, then delete the original library file
// and rename our new one. This ensures that there is a minimum possibility of things
// going wrong, for example if the process is killed mid-writing.
string tempFilePath = Path.Combine(Path.GetDirectoryName(this.targetPath), Guid.NewGuid().ToString());
using (FileStream targetStream = File.Create(tempFilePath))
{
LibraryWriter.Write(songs, playlists, songSourcePath, targetStream);
}
File.Delete(this.targetPath);
File.Move(tempFilePath, this.targetPath);
}
}
}``` |
2218828f-ae5d-499f-a34a-de013c52bc47 | {
"language": "C#"
} | ```c#
namespace Mitternacht.Common
{
public class TimeConstants
{
public const int WaitForForum = 500;
public const int TeamUpdate = 60 * 1000;
public const int Birthday = 60 * 1000;
}
}
```
Change Teamupdate time interval to 180s. | ```c#
namespace Mitternacht.Common
{
public class TimeConstants
{
public const int WaitForForum = 500;
public const int TeamUpdate = 3 * 60 * 1000;
public const int Birthday = 60 * 1000;
}
}
``` |
a2d44c7d-f99c-47b0-88ac-680b6309d585 | {
"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;
}
}
}
``` |
d84f18e8-3941-499c-98d4-5209b422ca55 | {
"language": "C#"
} | ```c#
namespace Fixie.Behaviors
{
public interface CaseBehavior
{
void Execute(Case @case, object instance);
}
}```
Add comment to demo teamcity | ```c#
namespace Fixie.Behaviors
{
public interface CaseBehavior
{
void Execute(Case @case, object instance); //comment to demo teamcity
}
}
``` |
f747c9f5-99ed-4cf5-8e50-3ea823c6b08e | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Infopulse.EDemocracy.Model.BusinessEntities
{
public class UserDetailInfo : BaseEntity
{
[JsonIgnore]
public int UserID { get; set; }
[Required]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
public string ZipCode { get; set; }
[Required]
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
[Required]
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
[JsonIgnore]
public string CreatedBy { get; set; }
[JsonIgnore]
public DateTime CreatedDate { get; set; }
[JsonIgnore]
public string ModifiedBy { get; set; }
[JsonIgnore]
public DateTime? ModifiedDate { get; set; }
public User User { get; set; }
public List<Petition> CreatedPetitions { get; set; }
public List<Petition> SignedPetitions { get; set; }
public UserDetailInfo()
{
this.CreatedPetitions = new List<Petition>();
}
}
}
```
Make default value of SignedPetitions as array. | ```c#
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Infopulse.EDemocracy.Model.BusinessEntities
{
public class UserDetailInfo : BaseEntity
{
[JsonIgnore]
public int UserID { get; set; }
[Required]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
public string ZipCode { get; set; }
[Required]
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
[Required]
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
[JsonIgnore]
public string CreatedBy { get; set; }
[JsonIgnore]
public DateTime CreatedDate { get; set; }
[JsonIgnore]
public string ModifiedBy { get; set; }
[JsonIgnore]
public DateTime? ModifiedDate { get; set; }
public User User { get; set; }
public List<Petition> CreatedPetitions { get; set; }
public List<Petition> SignedPetitions { get; set; }
public UserDetailInfo()
{
this.CreatedPetitions = new List<Petition>();
this.SignedPetitions = new List<Petition>();
}
}
}
``` |
a8d5f227-09fc-4dab-bfeb-96161824ed17 | {
"language": "C#"
} | ```c#
using System;
using EntityFramework.Mapping;
using Xunit;
using Tracker.SqlServer.CodeFirst;
using Tracker.SqlServer.CodeFirst.Entities;
using Tracker.SqlServer.Entities;
using EntityFramework.Extensions;
using Task = Tracker.SqlServer.Entities.Task;
namespace Tracker.SqlServer.Test
{
/// <summary>
/// Summary description for MappingObjectContext
/// </summary>
public class MappingObjectContext
{
[Fact]
public void GetEntityMapTask()
{
//var db = new TrackerEntities();
//var metadata = db.MetadataWorkspace;
//var map = db.Tasks.GetEntityMap<Task>();
//Assert.Equal("[dbo].[Task]", map.TableName);
}
[Fact]
public void GetEntityMapAuditData()
{
var db = new TrackerContext();
var resolver = new MetadataMappingProvider();
var map = resolver.GetEntityMap(typeof(AuditData), db);
//var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>();
Assert.Equal("[dbo].[Audit]", map.TableName);
}
[Fact]
public void GetInheritedEntityMapAuditData()
{
var db = new TrackerContext();
var resolver = new MetadataMappingProvider();
var map = resolver.GetEntityMap(typeof(CodeFirst.Entities.Task), db);
//var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>();
Assert.Equal("[dbo].[Task]", map.TableName);
}
}
}
```
Update tests with new specifications of Mapping | ```c#
using System;
using EntityFramework.Mapping;
using Xunit;
using Tracker.SqlServer.CodeFirst;
using Tracker.SqlServer.CodeFirst.Entities;
using Tracker.SqlServer.Entities;
using EntityFramework.Extensions;
using Task = Tracker.SqlServer.Entities.Task;
namespace Tracker.SqlServer.Test
{
/// <summary>
/// Summary description for MappingObjectContext
/// </summary>
public class MappingObjectContext
{
[Fact]
public void GetEntityMapTask()
{
//var db = new TrackerEntities();
//var metadata = db.MetadataWorkspace;
//var map = db.Tasks.GetEntityMap<Task>();
//Assert.Equal("[dbo].[Task]", map.TableName);
}
[Fact]
public void GetEntityMapAuditData()
{
var db = new TrackerContext();
var resolver = new MetadataMappingProvider();
var map = resolver.GetEntityMap(typeof(AuditData), db);
//var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>();
Assert.Equal("Audit", map.TableName);
Assert.Equal("dbo", map.SchemaName);
}
[Fact]
public void GetInheritedEntityMapAuditData()
{
var db = new TrackerContext();
var resolver = new MetadataMappingProvider();
var map = resolver.GetEntityMap(typeof(CodeFirst.Entities.Task), db);
//var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>();
Assert.Equal("Task", map.TableName);
Assert.Equal("dbo", map.SchemaName);
}
}
}
``` |
6ca58803-3298-475a-a2de-4272f60c9aaa | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main
/// executes a FindByTag on the scene, which will get worse and worse with more tagged objects.
/// </summary>
public static class CameraCache
{
private static Camera cachedCamera;
/// <summary>
/// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet.
/// </summary>
public static Camera Main
{
get
{
// ReSharper disable once ConvertIfStatementToReturnStatement
if (cachedCamera == null)
{
return Refresh(Camera.main);
}
return cachedCamera;
}
}
/// <summary>
/// Set the cached camera to a new reference and return it
/// </summary>
/// <param name="newMain">New main camera to cache</param>
public static Camera Refresh(Camera newMain)
{
return cachedCamera = newMain;
}
}
}
```
Remove in-code resharper disable statement | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main
/// executes a FindByTag on the scene, which will get worse and worse with more tagged objects.
/// </summary>
public static class CameraCache
{
private static Camera cachedCamera;
/// <summary>
/// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet.
/// </summary>
public static Camera Main
{
get
{
if (cachedCamera == null)
{
return Refresh(Camera.main);
}
return cachedCamera;
}
}
/// <summary>
/// Set the cached camera to a new reference and return it
/// </summary>
/// <param name="newMain">New main camera to cache</param>
public static Camera Refresh(Camera newMain)
{
return cachedCamera = newMain;
}
}
}
``` |
03629b1e-da55-4c3d-a111-4c2148bf939e | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MicrogameCollection))]
public class MicrogameCollectionEditor : Editor
{
public override void OnInspectorGUI()
{
MicrogameCollection collection = (MicrogameCollection)target;
if (GUILayout.Button("Update Microgames"))
{
collection.updateMicrogames();
EditorUtility.SetDirty(collection);
}
if (GUILayout.Button("Update Build Path"))
{
collection.updateBuildPath();
EditorUtility.SetDirty(collection);
}
DrawDefaultInspector();
}
}
```
Adjust collection editor to list by milestone | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
[CustomEditor(typeof(MicrogameCollection))]
public class MicrogameCollectionEditor : Editor
{
MicrogameCollection collection;
private List<MicrogameList> microgames;
private class MicrogameList
{
public string milestoneName;
public bool show = false;
public List<string> idList;
public MicrogameList()
{
idList = new List<string>();
}
}
private void OnEnable()
{
collection = (MicrogameCollection)target;
setMicrogames();
}
void setMicrogames()
{
microgames = new List<MicrogameList>();
var collectionMicrogames = collection.microgames;
var milestoneNames = Enum.GetNames(typeof(MicrogameTraits.Milestone));
for (int i = milestoneNames.Length - 1; i >= 0; i--)
{
var milestoneMicrogames = collectionMicrogames.Where(a => (int)a.difficultyTraits[0].milestone == i);
var newList = new MicrogameList();
newList.milestoneName = milestoneNames[i];
foreach (var milestoneMicrogame in milestoneMicrogames)
{
newList.idList.Add(milestoneMicrogame.microgameId);
}
microgames.Add(newList);
}
}
public override void OnInspectorGUI()
{
if (GUILayout.Button("Update Microgames"))
{
collection.updateMicrogames();
setMicrogames();
EditorUtility.SetDirty(collection);
}
if (GUILayout.Button("Update Build Path"))
{
collection.updateBuildPath();
EditorUtility.SetDirty(collection);
}
GUILayout.Label("Indexed Microgames:");
var names = Enum.GetNames(typeof(MicrogameTraits.Milestone));
foreach (var microgameList in microgames)
{
microgameList.show = EditorGUILayout.Foldout(microgameList.show, microgameList.milestoneName);
if (microgameList.show)
{
foreach (var microgameId in microgameList.idList)
{
EditorGUILayout.LabelField(" " + microgameId);
}
}
}
}
}
``` |
448a4ff1-958b-40e7-abea-174a6f1e8a2d | {
"language": "C#"
} | ```c#
@{
var pages = Pages;
}
<ul class="nav navbar-nav navbar-right">
@foreach (var p in pages)
{
@Html.Partial("_PageNavigation", p)
}
@if (Settings.ShowSharedFoldersInMenus)
{
<li>
@SharedFoldersLink()
</li>
}
</ul>```
Fix bug in default nav for shared folders link | ```c#
@{
var pages = Pages;
}
<ul class="nav navbar-nav navbar-right">
@foreach (var p in pages)
{
@Html.Partial("_PageNavigation", p)
}
@if (Settings.ShowSharedFoldersInMenus && SharedFoldersLinkIsAvailable())
{
<li>
@SharedFoldersLink()
</li>
}
</ul>``` |
5d60499c-ddbc-43a7-81df-9bb461b7dbab | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
private static IEnumerable<CodeInstruction> Replacer(IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode opcode)
{
if (from == null)
throw new ArgumentException("Unexpected null argument", nameof(from));
if (to == null)
throw new ArgumentException("Unexpected null argument", nameof(to));
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = opcode;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
return Replacer(instructions, from, to, OpCodes.Call);
}
public static IEnumerable<CodeInstruction> ConstructorReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
return Replacer(instructions, from, to, OpCodes.Newobj);
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
}```
Simplify MethodReplacer and keep backwards compatibility | ```c#
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
if (from == null)
throw new ArgumentException("Unexpected null argument", nameof(from));
if (to == null)
throw new ArgumentException("Unexpected null argument", nameof(to));
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = to.IsConstructor ? OpCodes.Newobj : OpCodes.Call;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
}``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.