doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
a036be2a-4c3a-4481-a5ad-044621b26f91 | {
"language": "C#"
} | ```c#
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;
namespace SmartCam.Controllers
{
public class SmartCamController : Controller
{
private static byte[] currentImage = new byte[0];
[HttpPost]
public string PostImage(HttpPostedFileBase file)
{
Stream fileStream = file.InputStream;
using (MemoryStream ms = new MemoryStream())
{
fileStream.CopyTo(ms);
currentImage = ms.GetBuffer();
}
return "Success";
}
[HttpGet]
public FileResult GetPicture()
{
return new FileStreamResult(new MemoryStream(currentImage), "image/jpeg");
}
[HttpGet]
public string SendNotification()
{
var fromAddress = new MailAddress(from, "From Name");
var toAddress = new MailAddress(to, "To Name");
const string fromPassword = ;
const string subject = "SmartCam";
const string body = "Motion Detected!";
using (SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
})
{
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
return "Success";
}
}
}
```
Add an endpoint for the view page | ```c#
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;
namespace SmartCam.Controllers
{
public class SmartCamController : Controller
{
private static byte[] currentImage = new byte[0];
[HttpPost]
public string PostImage(HttpPostedFileBase file)
{
Stream fileStream = file.InputStream;
using (MemoryStream ms = new MemoryStream())
{
fileStream.CopyTo(ms);
currentImage = ms.GetBuffer();
}
return "Success";
}
[HttpGet]
public FileResult GetPicture()
{
return new FileStreamResult(new MemoryStream(currentImage), "image/jpeg");
}
[HttpGet]
public ActionResult ShowFeed()
{
return View();
}
[HttpGet]
public string SendNotification()
{
var fromAddress = new MailAddress(from, "From Name");
var toAddress = new MailAddress(to, "To Name");
const string fromPassword = ;
const string subject = "SmartCam";
const string body = "Motion Detected!";
using (SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
})
{
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
return "Success";
}
}
}
``` |
4d416e84-5558-4604-b0c4-b67bedfe48cb | {
"language": "C#"
} | ```c#
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
namespace XmlParserWpf
{
public class FilesViewModel: ObservableCollection<FilesListItem>
{
public const int NoneSelection = -1;
private int _selectedIndex = NoneSelection;
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
if (_selectedIndex != value)
{
_selectedIndex = value;
OnPropertyChanged(new PropertyChangedEventArgs("SelectedIndex"));
OnPropertyChanged(new PropertyChangedEventArgs("SelectedFile"));
}
}
}
public FilesListItem SelectedFile => (SelectedIndex != NoneSelection ? this[SelectedIndex] : null);
public void AddAndSelect(FilesListItem item)
{
Add(item);
SelectedIndex = IndexOf(item);
}
public bool HasFile(string path)
{
return this.Any(x => x.Path.Equals(path));
}
public void SelectIfExists(string path)
{
if (HasFile(path))
SelectedIndex = IndexOf(this.First(x => x.Path.Equals(path)));
}
public void RemoveSelected()
{
if (SelectedIndex < 0)
return;
RemoveAt(SelectedIndex);
if (Count == 0)
SelectedIndex = NoneSelection;
}
}
}
```
Fix IndexOutOfBounds exception on application closing | ```c#
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
namespace XmlParserWpf
{
public class FilesViewModel: ObservableCollection<FilesListItem>
{
public const int NoneSelection = -1;
private int _selectedIndex = NoneSelection;
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
if (_selectedIndex != value)
{
_selectedIndex = value;
OnPropertyChanged(new PropertyChangedEventArgs("SelectedIndex"));
OnPropertyChanged(new PropertyChangedEventArgs("SelectedFile"));
}
}
}
public FilesListItem SelectedFile => ((Count > 0) && (SelectedIndex != NoneSelection)) ? this[SelectedIndex] : null;
public void AddAndSelect(FilesListItem item)
{
Add(item);
SelectedIndex = IndexOf(item);
}
public bool HasFile(string path)
{
return this.Any(x => x.Path.Equals(path));
}
public void SelectIfExists(string path)
{
if (HasFile(path))
SelectedIndex = IndexOf(this.First(x => x.Path.Equals(path)));
}
public void RemoveSelected()
{
if (SelectedIndex < 0)
return;
RemoveAt(SelectedIndex);
if (Count == 0)
SelectedIndex = NoneSelection;
}
}
}
``` |
b838082f-9f59-482a-90d1-1052808928c7 | {
"language": "C#"
} | ```c#
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Persistence.MongoDB;
using SO115App.Models.Servizi.Infrastruttura.GestioneTrasferimentiChiamate.CodiciChiamate;
using System.Collections.Generic;
namespace SO115App.Persistence.MongoDB.GestioneTrasferimentiChiamate.CodiciChiamate
{
public class GetCodiciChiamate : IGetCodiciChiamate
{
private readonly DbContext _dbContext;
public GetCodiciChiamate(DbContext dbContext) => _dbContext = dbContext;
public List<string> Get(string CodSede)
{
return _dbContext.RichiestaAssistenzaCollection.AsQueryable()
.Where(c => c.TestoStatoRichiesta == "C" && c.CodSOCompetente == CodSede)
.Select(c => c.Codice)
.ToList();
}
}
}
```
Fix gestione codici chiamata in Trasferimento Chiamata | ```c#
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Organigramma;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.Models.Servizi.Infrastruttura.GestioneTrasferimentiChiamate.CodiciChiamate;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.ServizioSede;
using System.Collections.Generic;
using System.Linq;
namespace SO115App.Persistence.MongoDB.GestioneTrasferimentiChiamate.CodiciChiamate
{
public class GetCodiciChiamate : IGetCodiciChiamate
{
private readonly DbContext _dbContext;
private readonly IGetAlberaturaUnitaOperative _getAlberaturaUnitaOperative;
public GetCodiciChiamate(DbContext dbContext, IGetAlberaturaUnitaOperative getAlberaturaUnitaOperative)
{
_dbContext = dbContext;
_getAlberaturaUnitaOperative = getAlberaturaUnitaOperative;
}
public List<string> Get(string CodSede)
{
var listaSediAlberate = _getAlberaturaUnitaOperative.ListaSediAlberata();
var pinNodi = new List<PinNodo>();
pinNodi.Add(new PinNodo(CodSede, true));
foreach (var figlio in listaSediAlberate.GetSottoAlbero(pinNodi))
{
pinNodi.Add(new PinNodo(figlio.Codice, true));
}
var filtroSediCompetenti = Builders<RichiestaAssistenza>.Filter
.In(richiesta => richiesta.CodSOCompetente, pinNodi.Select(uo => uo.Codice));
var lista = _dbContext.RichiestaAssistenzaCollection.Find(filtroSediCompetenti).ToList();
return lista.Where(c => c.TestoStatoRichiesta == "C")
.Select(c => c.Codice).ToList();
}
}
}
``` |
7938de17-5158-47f4-b3c7-729dcbbdc769 | {
"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.Linq;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Beatmaps.Formats
{
/// <summary>
/// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s
/// <remarks>
/// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>.
/// Doing so will override any existing <see cref="Beatmap"/> decoders.
/// </remarks>
/// </summary>
public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder
{
public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION)
: base(version)
{
ApplyOffsets = false;
}
public new static void Register()
{
AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last())));
}
protected override TimingControlPoint CreateTimingControlPoint()
=> new LegacyDifficultyCalculatorControlPoint();
private class LegacyDifficultyCalculatorControlPoint : TimingControlPoint
{
public override double BeatLength { get; set; } = DEFAULT_BEAT_LENGTH;
}
}
}
```
Add difficulty calculator beatmap decoder fallback | ```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.Linq;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Beatmaps.Formats
{
/// <summary>
/// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s
/// <remarks>
/// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>.
/// Doing so will override any existing <see cref="Beatmap"/> decoders.
/// </remarks>
/// </summary>
public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder
{
public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION)
: base(version)
{
ApplyOffsets = false;
}
public new static void Register()
{
AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last())));
SetFallbackDecoder<Beatmap>(() => new LegacyDifficultyCalculatorBeatmapDecoder());
}
protected override TimingControlPoint CreateTimingControlPoint()
=> new LegacyDifficultyCalculatorControlPoint();
private class LegacyDifficultyCalculatorControlPoint : TimingControlPoint
{
public override double BeatLength { get; set; } = DEFAULT_BEAT_LENGTH;
}
}
}
``` |
3e3b211b-1ee0-462c-b9c8-bc7a923e2ef2 | {
"language": "C#"
} | ```c#
using System;
using HexWorld.Enums;
namespace HexWorld
{
public class Tile
{
public TileTypes Type { get; set; }
public bool IsWater { get; set; }
public string Printable { get; set; }
public Tile(TileTypes type)
{
ChangeTile(type);
}
public void ChangeTile(TileTypes type)
{
Type = type;
switch (Type)
{
case TileTypes.Ocean:
IsWater = true;
// Printable = "▓▓▓";
Printable = " ";
break;
case TileTypes.Desert:
IsWater = false;
Printable = "░░░";
break;
case TileTypes.Mountain:
IsWater = false;
Printable = "╔╬╗";
break;
case TileTypes.Hill:
IsWater = false;
Printable = "▅▂▅";
break;
case TileTypes.Grassland:
IsWater = false;
Printable = "▒▒▒";
break;
case TileTypes.Steppe:
IsWater = false;
Printable = "░▒░";
break;
case TileTypes.Tundra:
IsWater = false;
Printable = "***";
break;
default:
throw new ArgumentException("Unknown Tile Type");
}
}
public override string ToString()
{
return Printable;
}
}
}```
Test data for last 3 tile types. | ```c#
using System;
using HexWorld.Enums;
namespace HexWorld
{
public class Tile
{
public TileTypes Type { get; set; }
public bool IsWater { get; set; }
public string Printable { get; set; }
public Tile(TileTypes type)
{
ChangeTile(type);
}
public void ChangeTile(TileTypes type)
{
Type = type;
switch (Type)
{
case TileTypes.Ocean:
IsWater = true;
// Printable = "▓▓▓";
Printable = " ";
break;
case TileTypes.Desert:
IsWater = false;
Printable = "░░░";
break;
case TileTypes.Mountain:
IsWater = false;
Printable = "╔╬╗";
break;
case TileTypes.Hill:
IsWater = false;
Printable = "▅▂▅";
break;
case TileTypes.Grassland:
IsWater = false;
Printable = "▒▒▒";
break;
case TileTypes.Steppe:
IsWater = false;
Printable = "░▒░";
break;
case TileTypes.Tundra:
IsWater = false;
Printable = "***";
break;
case TileTypes.Jungle:
IsWater = false;
Printable = "╫╫╫";
break;
case TileTypes.Forest:
IsWater = false;
Printable = "┼┼┼";
break;
case TileTypes.Swamp:
IsWater = false;
Printable = "▚▞▜";
break;
default:
throw new ArgumentException("Unknown Tile Type");
}
}
public override string ToString()
{
return Printable;
}
}
}``` |
0b97a71f-576a-47b6-a416-b935d3474c9f | {
"language": "C#"
} | ```c#
namespace testproj
{
using System;
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
dotMemory.Check(
memory =>
{
var str1 = "1";
var str2 = "2";
var str3 = "3";
Assert.LessOrEqual(2, memory.ObjectsCount);
Console.WriteLine(str1 + str2 + str3);
});
}
}
}
```
Add broken test to testproj | ```c#
namespace testproj
{
using System;
using System.Collections.Generic;
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var strs = new List<string>();
var memoryCheckPoint = dotMemory.Check();
strs.Add(GenStr());
strs.Add(GenStr());
strs.Add(GenStr());
dotMemory.Check(
memory =>
{
var strCount = memory
.GetDifference(memoryCheckPoint)
.GetNewObjects()
.GetObjects(i => i.Type == typeof(string))
.ObjectsCount;
Assert.LessOrEqual(strCount, 2);
});
strs.Clear();
}
[Test]
public void TestMethod2()
{
var strs = new List<string>();
var memoryCheckPoint = dotMemory.Check();
strs.Add(GenStr());
strs.Add(GenStr());
dotMemory.Check(
memory =>
{
var strCount = memory
.GetDifference(memoryCheckPoint)
.GetNewObjects()
.GetObjects(i => i.Type == typeof(string))
.ObjectsCount;
Assert.LessOrEqual(strCount, 2);
});
strs.Clear();
}
private static string GenStr()
{
return Guid.NewGuid().ToString();
}
}
}
``` |
38a4c9a5-7b4f-4bc5-b27f-736d6a1c1bb4 | {
"language": "C#"
} | ```c#
using UnityEngine;
using UnityEngine.Networking;
public class PlayerState : NetworkBehaviour {
[SyncVar]
string fakingTheory;
[SyncVar]
int score;
void Start()
{
fakingTheory = null;
score = 0;
}
[Command]
public void CmdSetFakingState(string newFakingTheory)
{
fakingTheory = newFakingTheory;
}
[Command]
public void CmdAddScore(int value)
{
score += value;
}
public bool IsFaking()
{
return (fakingTheory != null);
}
void OnGUI()
{
if (!isLocalPlayer)
{
return;
}
GUI.BeginGroup(new Rect(Screen.width / 2 - 100, Screen.height - 100, 200, 200));
GUILayout.Label("Score: " + score);
if (IsFaking())
{
GUILayout.Label("Faking using " + fakingTheory);
}
GUI.EndGroup();
}
}
```
Fix the player score counter (IsFaking always returned true) | ```c#
using System;
using UnityEngine;
using UnityEngine.Networking;
public class PlayerState : NetworkBehaviour {
[SyncVar]
string fakingTheory;
[SyncVar]
int score;
void Start()
{
fakingTheory = null;
score = 0;
}
[Command]
public void CmdSetFakingState(string newFakingTheory)
{
fakingTheory = newFakingTheory;
}
[Command]
public void CmdAddScore(int value)
{
score += value;
}
public bool IsFaking()
{
return !String.IsNullOrEmpty(fakingTheory);
}
void OnGUI()
{
if (!isLocalPlayer)
{
return;
}
GUI.BeginGroup(new Rect(Screen.width / 2 - 100, Screen.height - 100, 200, 200));
GUILayout.Label("Score: " + score);
if (IsFaking())
{
GUILayout.Label("Faking using " + fakingTheory);
}
GUI.EndGroup();
}
}
``` |
16a4901f-43fd-46fa-b866-77e9fdee9656 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Gitter.Services.Abstract;
namespace Gitter.Services.Concrete
{
public class BackgroundTaskService : IBackgroundTaskService
{
public Dictionary<string, string> Tasks
{
get
{
return new Dictionary<string, string>
{
{"NotificationsBackgroundTask", "Gitter.Tasks"}
};
}
}
public async Task RegisterTasksAsync()
{
foreach (var kvTask in Tasks)
{
if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == kvTask.Key))
break;
await RegisterTaskAsync(kvTask.Key, kvTask.Value);
}
}
private async Task RegisterTaskAsync(string taskName, string taskNamespace)
{
var requestAccess = await BackgroundExecutionManager.RequestAccessAsync();
if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity ||
requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
{
var taskBuilder = new BackgroundTaskBuilder
{
Name = taskName,
TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName)
};
// Set the condition trigger that feels right for you
taskBuilder.SetTrigger(new TimeTrigger(15, false));
taskBuilder.Register();
}
}
}
}
```
Add conditions to background tasks | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Gitter.Services.Abstract;
namespace Gitter.Services.Concrete
{
public class BackgroundTaskService : IBackgroundTaskService
{
public Dictionary<string, string> Tasks
{
get
{
return new Dictionary<string, string>
{
{"NotificationsBackgroundTask", "Gitter.Tasks"}
};
}
}
public async Task RegisterTasksAsync()
{
foreach (var kvTask in Tasks)
{
if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == kvTask.Key))
break;
await RegisterTaskAsync(kvTask.Key, kvTask.Value);
}
}
private async Task RegisterTaskAsync(string taskName, string taskNamespace)
{
var requestAccess = await BackgroundExecutionManager.RequestAccessAsync();
if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity ||
requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
{
var taskBuilder = new BackgroundTaskBuilder
{
Name = taskName,
TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName)
};
// Set the condition trigger that feels right for you
taskBuilder.SetTrigger(new TimeTrigger(15, false));
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.UserNotPresent));
taskBuilder.Register();
}
}
}
}
``` |
3830493e-f4da-4a31-83f5-f2f184a4f9da | {
"language": "C#"
} | ```c#
using System;
namespace Mindscape.Raygun4Net
{
public class RaygunSettings
{
private static RaygunSettings settings;
private const string DefaultApiEndPoint = "https://api.raygun.io/entries";
private const string DefaultPulseEndPoint = "https://api.raygun.io/events";
public static RaygunSettings Settings
{
get
{
return settings ?? (settings = new RaygunSettings { ApiEndpoint = new Uri(DefaultApiEndPoint), PulseEndpoint = new Uri(DefaultPulseEndPoint) });
}
}
public Uri ApiEndpoint { get; set; }
public Uri PulseEndpoint{ get; set; }
}
}
```
Add option to mark exceptions as observed | ```c#
using System;
namespace Mindscape.Raygun4Net
{
public class RaygunSettings
{
private static RaygunSettings settings;
private const string DefaultApiEndPoint = "https://api.raygun.io/entries";
private const string DefaultPulseEndPoint = "https://api.raygun.io/events";
public static RaygunSettings Settings
{
get
{
return settings ?? (settings = new RaygunSettings { ApiEndpoint = new Uri(DefaultApiEndPoint), PulseEndpoint = new Uri(DefaultPulseEndPoint) });
}
}
public Uri ApiEndpoint { get; set; }
public Uri PulseEndpoint{ get; set; }
public bool SetUnobservedTaskExceptionsAsObserved { get; set; }
}
}
``` |
581f7ba3-5c6b-4e45-a121-bbe3896b70ec | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MatterHackers.Agg.UI
{
public class RootedObjectEventHandler
{
EventHandler InternalEvent;
public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
{
InternalEvent += functionToCallOnEvent;
functionThatWillBeCalledToUnregisterEvent += (sender, e) =>
{
InternalEvent -= functionToCallOnEvent;
};
}
public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
{
InternalEvent -= functionToCallOnEvent;
// After we remove it it will still be removed again in the functionThatWillBeCalledToUnregisterEvent
// But it is valid to attempt remove more than once.
}
public void CallEvents(Object sender, EventArgs e)
{
if (InternalEvent != null)
{
InternalEvent(this, e);
}
}
}
}
```
Put in some debugging code for looking at what functions have been added to the rooted event handler. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MatterHackers.Agg.UI
{
public class RootedObjectEventHandler
{
#if DEBUG
private event EventHandler InternalEventForDebug;
private List<EventHandler> DebugEventDelegates = new List<EventHandler>();
private event EventHandler InternalEvent
{
//Wraps the PrivateClick event delegate so that we can track which events have been added and clear them if necessary
add
{
InternalEventForDebug += value;
DebugEventDelegates.Add(value);
}
remove
{
InternalEventForDebug -= value;
DebugEventDelegates.Remove(value);
}
}
#else
EventHandler InternalEvent;
#endif
public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
{
InternalEvent += functionToCallOnEvent;
functionThatWillBeCalledToUnregisterEvent += (sender, e) =>
{
InternalEvent -= functionToCallOnEvent;
};
}
public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
{
InternalEvent -= functionToCallOnEvent;
// After we remove it it will still be removed again in the functionThatWillBeCalledToUnregisterEvent
// But it is valid to attempt remove more than once.
}
public void CallEvents(Object sender, EventArgs e)
{
#if DEBUG
if (InternalEventForDebug != null)
{
InternalEventForDebug(this, e);
}
#else
if (InternalEvent != null)
{
InternalEvent(this, e);
}
#endif
}
}
}
``` |
20bda35c-2762-4267-8af5-1e3ac0e7a16b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GrienerTest
{
public partial class PolygonClip
{
#if false
void insert(node *ins, node *first, node *last)
{
node *aux=first;
while(aux != last && aux->alpha < ins->alpha) aux = aux->next;
ins->next = aux;
ins->prev = aux->prev;
ins->prev->next = ins;
ins->next->prev = ins;
}
#endif
void insert(Node ins,Node first,Node last)
{
Node aux = first;
while (aux != last && aux.alpha < ins.alpha) aux = aux.next;
ins.next = aux;
ins.prev = aux.prev;
ins.prev.next = ins;
ins.next.prev = ins;
}
}
}
```
Add in check for null pointers. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GrienerTest
{
public partial class PolygonClip
{
#if false
void insert(node *ins, node *first, node *last)
{
node *aux=first;
while(aux != last && aux->alpha < ins->alpha) aux = aux->next;
ins->next = aux;
ins->prev = aux->prev;
ins->prev->next = ins;
ins->next->prev = ins;
}
#endif
void insert(Node ins,Node first,Node last)
{
Node aux = first;
while (aux != last && aux.alpha < ins.alpha) aux = aux.next;
ins.next = aux;
ins.prev = aux.prev;
/*
* Feb 2017. Check against null pointer
*/
if (ins.prev != null) {
ins.prev.next = ins;
}
if (ins.next != null) {
ins.next.prev = ins;
}
}
}
}
``` |
b1081316-1ffb-49b8-89c2-815d129a7328 | {
"language": "C#"
} | ```c#
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
</address>```
Add nick wolf contact info. | ```c#
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Nicolas:</strong> <a href="mailto:nick.wolf@zirmed.com">nick.wolf@zirmed.com</a>
</address>``` |
cd4fc3b9-30ae-4a2b-926a-17471bfa0ef7 | {
"language": "C#"
} | ```c#
using System;
using Mono.TextEditor;
using ICSharpCode.NRefactory;
namespace JustEnoughVi
{
public class ChangeInnerBlock : ChangeCommand
{
public ChangeInnerBlock(TextEditorData editor, char openingChar, char closingChar)
: base(editor, TextObject.InnerBlock, openingChar, closingChar)
{
}
protected override void Run()
{
CommandRange range = _selector();
ChangeRange(range);
if (range != CommandRange.Empty)
{
// Move caret inside if it is on on opening character and block is empty
if (range.Length == 0 && Editor.Caret.Offset < range.Start)
Editor.Caret.Offset++;
else
{
// if block still has two newlines inside, then drop inside block and indent
int del1 = NewLine.GetDelimiterLength(Editor.Text[range.Start - 1], Editor.Text[range.Start]);
if (del1 > 0)
{
int del2Start = range.Start - 1 + del1;
int del2 = NewLine.GetDelimiterLength(Editor.Text[del2Start],
Editor.Text[del2Start + 1]);
if (del2 > 0)
IndentInsideBlock(range.Start);
}
}
}
}
private void IndentInsideBlock(int blockStart)
{
int end = blockStart;
while (Char.IsWhiteSpace(Editor.Text[end]))
end++;
Editor.SetSelection(blockStart, end);
Editor.DeleteSelectedText();
MiscActions.InsertNewLine(Editor);
}
}
}
```
Fix indentation when changing inside multiline block | ```c#
using System;
using Mono.TextEditor;
using ICSharpCode.NRefactory.Utils;
using ICSharpCode.NRefactory;
namespace JustEnoughVi
{
public class ChangeInnerBlock : ChangeCommand
{
public ChangeInnerBlock(TextEditorData editor, char openingChar, char closingChar)
: base(editor, TextObject.InnerBlock, openingChar, closingChar)
{
}
protected override void Run()
{
CommandRange range = _selector();
ChangeRange(range);
if (range != CommandRange.Empty)
{
// Move caret inside if it is on on opening character and block is empty
if (range.Length == 0 && Editor.Caret.Offset < range.Start)
Editor.Caret.Offset++;
else
{
// if block still has two newlines inside, then drop inside block and indent
int del1 = NewLine.GetDelimiterLength(Editor.Text[range.Start - 1], Editor.Text[range.Start]);
if (del1 > 0)
{
int del2Start = range.Start - 1 + del1;
int del2 = NewLine.GetDelimiterLength(Editor.Text[del2Start],
Editor.Text[del2Start + 1]);
if (del2 > 0)
IndentInsideBlock(range.Start - 2);
}
}
}
}
private void IndentInsideBlock(int openingChar)
{
string indentation = Editor.GetLineIndent(Editor.OffsetToLineNumber(openingChar));
if (indentation != null && indentation.Length > 0)
Editor.Insert(Editor.Caret.Offset, indentation);
MiscActions.InsertTab(Editor);
}
}
}
``` |
db6d9789-b450-4455-bab9-f6792a8859fc | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DynaShape")]
[assembly: AssemblyDescription("Open-source Dynamo plugin for constraint-based form finding, optimization and physics simulation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DynaShape")]
[assembly: AssemblyCopyright("MIT License © 2017 Long Nguyen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("157ad178-ee17-46e9-b6dc-c50eb9dcca60")]
[assembly: AssemblyVersion("0.3.1.2")]
[assembly: AssemblyFileVersion("0.3.1.2")]
```
Set AssemblyVersion number correctly to 0.3.2 | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DynaShape")]
[assembly: AssemblyDescription("Open-source Dynamo plugin for constraint-based form finding, optimization and physics simulation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DynaShape")]
[assembly: AssemblyCopyright("MIT License © 2017 Long Nguyen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("157ad178-ee17-46e9-b6dc-c50eb9dcca60")]
[assembly: AssemblyVersion("0.3.2.0")]
[assembly: AssemblyFileVersion("0.3.2.0")]
``` |
40ec705d-aa3c-4b66-961c-4a2cda6fec95 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Text;
namespace EvilDICOM.Core.IO.Writing
{
public class DICOMBinaryWriter : IDisposable
{
private readonly BinaryWriter _writer;
/// <summary>
/// Constructs a new writer from a file path.
/// </summary>
/// <param name="filePath">path to the file to be written</param>
public DICOMBinaryWriter(string filePath)
{
_writer = new BinaryWriter(
File.Open(filePath, FileMode.Create),
Encoding.UTF8);
}
public DICOMBinaryWriter(Stream stream)
{
_writer = new BinaryWriter(stream, Encoding.UTF8);
}
public void Dispose()
{
_writer.Dispose();
}
public void Write(byte b)
{
_writer.Write(b);
}
public void Write(byte[] bytes)
{
_writer.Write(bytes);
}
public void Write(char[] chars)
{
_writer.Write(chars);
}
public void Write(string chars)
{
char[] asCharArray = chars.ToCharArray(0, chars.Length);
Write(asCharArray);
}
public void WriteNullBytes(int numberToWrite)
{
for (int i = 0; i < numberToWrite; i++)
{
Write(0x00);
}
}
}
}```
Use portable ToCharArray overload yielding equivalent result | ```c#
using System;
using System.IO;
using System.Text;
namespace EvilDICOM.Core.IO.Writing
{
public class DICOMBinaryWriter : IDisposable
{
private readonly BinaryWriter _writer;
/// <summary>
/// Constructs a new writer from a file path.
/// </summary>
/// <param name="filePath">path to the file to be written</param>
public DICOMBinaryWriter(string filePath)
{
_writer = new BinaryWriter(
File.Open(filePath, FileMode.Create),
Encoding.UTF8);
}
public DICOMBinaryWriter(Stream stream)
{
_writer = new BinaryWriter(stream, Encoding.UTF8);
}
public void Dispose()
{
_writer.Dispose();
}
public void Write(byte b)
{
_writer.Write(b);
}
public void Write(byte[] bytes)
{
_writer.Write(bytes);
}
public void Write(char[] chars)
{
_writer.Write(chars);
}
public void Write(string chars)
{
char[] asCharArray = chars.ToCharArray();
Write(asCharArray);
}
public void WriteNullBytes(int numberToWrite)
{
for (int i = 0; i < numberToWrite; i++)
{
Write(0x00);
}
}
}
}``` |
4d0166e2-e37f-44e0-9849-91a5d36c6fb2 | {
"language": "C#"
} | ```c#
#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
_versionContext.Git = GitVersion();
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
}
```
Allow to run build even if git repo informations are not available | ```c#
#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
try
{
_versionContext.Git = GitVersion();
}
catch
{
_versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion();
}
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
}
``` |
00fb0737-81f1-49cd-a0c6-41b999c8fa81 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
class Program
{
[STAThread]
static void Main(string[] args)
{
var app = new Application();
var window = new Window();
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.WindowState = WindowState.Maximized;
window.Title = "SystemColors";
var content = new ListBox();
foreach (var prop in typeof(SystemColors).GetProperties().Where(p => p.PropertyType == typeof(SolidColorBrush)))
{
var brush = prop.GetValue(null) as SolidColorBrush;
var rect = new Rectangle() { Width = 100, Height = 20, Fill = brush };
var panel = new StackPanel() { Orientation = Orientation.Horizontal };
panel.Children.Add(new TextBlock() { Text = prop.Name, Width = 200 });
panel.Children.Add(rect);
panel.Children.Add(new TextBlock() { Text = brush.Color.ToString(), Margin = new Thickness(8, 0, 8, 0) });
content.Items.Add(panel);
}
window.Content = content;
app.Run(window);
}
}```
Add some code to dump known colors | ```c#
using System;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
class Program
{
[STAThread]
static void Main(string[] args)
{
var app = new Application();
var window = new Window();
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.WindowState = WindowState.Maximized;
window.Title = "SystemColors";
var content = new ListBox();
var sb = new StringBuilder();
foreach (var prop in typeof(SystemColors).GetProperties().Where(p => p.PropertyType == typeof(SolidColorBrush)))
{
var brush = prop.GetValue(null) as SolidColorBrush;
var rect = new Rectangle() { Width = 100, Height = 20, Fill = brush };
var panel = new StackPanel() { Orientation = Orientation.Horizontal };
panel.Children.Add(new TextBlock() { Text = prop.Name, Width = 200 });
panel.Children.Add(rect);
panel.Children.Add(new TextBlock() { Text = brush.Color.ToString(), Margin = new Thickness(8, 0, 8, 0) });
content.Items.Add(panel);
}
foreach (var prop in typeof(Colors).GetProperties().Where(p => p.PropertyType == typeof(Color)))
{
var color = (Color)prop.GetValue(null);
sb.AppendLine($"{color.R / 255.0}, {color.G / 255.0}, {color.B / 255.0},");
//sb.AppendLine($"{color.ScR}, {color.ScG}, {color.ScB},");
}
// Clipboard.SetText(sb.ToString());
window.Content = content;
app.Run(window);
}
}``` |
63124e48-7086-43ff-a13b-101e34025c94 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
namespace Twee2Z.Analyzer
{
public static class TweeAnalyzer
{
public static ObjectTree.Tree Parse(StreamReader input)
{
return Parse2(Lex(input));
}
public static ObjectTree.Tree Parse2(CommonTokenStream input)
{
System.Console.WriteLine("Parse twee file ...");
Twee.StartContext startContext = new Twee(input).start();
TweeVisitor visit = new TweeVisitor();
visit.Visit(startContext);
System.Console.WriteLine("Convert parse tree into object tree ...");
return visit.Tree;
}
public static CommonTokenStream Lex(StreamReader input)
{
System.Console.WriteLine("Lex twee file ...");
AntlrInputStream antlrStream = new AntlrInputStream(input.ReadToEnd());
return new CommonTokenStream(new LEX(antlrStream));
}
}
}
```
Revert "Revert "auswertung von tags gebessert"" | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
namespace Twee2Z.Analyzer
{
public static class TweeAnalyzer
{
public static ObjectTree.Tree Parse(StreamReader input)
{
return Parse2(Lex(input));
}
public static ObjectTree.Tree Parse2(CommonTokenStream input)
{
System.Console.WriteLine("Parse twee file ...");
Twee.StartContext startContext = new Twee(input).start();
TweeVisitor visit = new TweeVisitor();
visit.Visit(startContext);
System.Console.WriteLine("Convert parse tree into object tree ...");
return visit.Tree;
}
public static CommonTokenStream Lex(StreamReader input)
{
System.Console.WriteLine("Lex twee file ...");
AntlrInputStream antlrStream = new AntlrInputStream(input.ReadToEnd());
return new CommonTokenStream(new LEX(antlrStream));
}
}
}
``` |
edbcb700-f4af-4101-b688-944f5798ac2c | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using Eurofurence.App.Domain.Model.Abstractions;
using Eurofurence.App.Domain.Model.Sync;
using Eurofurence.App.Server.Services.Abstractions;
namespace Eurofurence.App.Server.Services.Storage
{
public class StorageService<T> : IStorageService
{
private readonly IEntityStorageInfoRepository _entityStorageInfoRepository;
private readonly string _entityType;
public StorageService(IEntityStorageInfoRepository entityStorageInfoRepository, string entityType)
{
_entityStorageInfoRepository = entityStorageInfoRepository;
_entityType = entityType;
}
public async Task TouchAsync()
{
var record = await GetEntityStorageRecordAsync();
record.LastChangeDateTimeUtc = DateTime.UtcNow;
await _entityStorageInfoRepository.ReplaceOneAsync(record);
}
public async Task ResetDeltaStartAsync()
{
var record = await GetEntityStorageRecordAsync();
record.DeltaStartDateTimeUtc = DateTime.UtcNow;
await _entityStorageInfoRepository.ReplaceOneAsync(record);
}
public Task<EntityStorageInfoRecord> GetStorageInfoAsync()
{
return GetEntityStorageRecordAsync();
}
private async Task<EntityStorageInfoRecord> GetEntityStorageRecordAsync()
{
var record = await _entityStorageInfoRepository.FindOneAsync(_entityType);
if (record == null)
{
record = new EntityStorageInfoRecord {EntityType = _entityType};
record.NewId();
record.Touch();
await _entityStorageInfoRepository.InsertOneAsync(record);
}
return record;
}
}
}```
Fix to ensure Delta start time is reset when storage is re-created | ```c#
using System;
using System.Threading.Tasks;
using Eurofurence.App.Domain.Model.Abstractions;
using Eurofurence.App.Domain.Model.Sync;
using Eurofurence.App.Server.Services.Abstractions;
namespace Eurofurence.App.Server.Services.Storage
{
public class StorageService<T> : IStorageService
{
private readonly IEntityStorageInfoRepository _entityStorageInfoRepository;
private readonly string _entityType;
public StorageService(IEntityStorageInfoRepository entityStorageInfoRepository, string entityType)
{
_entityStorageInfoRepository = entityStorageInfoRepository;
_entityType = entityType;
}
public async Task TouchAsync()
{
var record = await GetEntityStorageRecordAsync();
record.LastChangeDateTimeUtc = DateTime.UtcNow;
await _entityStorageInfoRepository.ReplaceOneAsync(record);
}
public async Task ResetDeltaStartAsync()
{
var record = await GetEntityStorageRecordAsync();
record.DeltaStartDateTimeUtc = DateTime.UtcNow;
await _entityStorageInfoRepository.ReplaceOneAsync(record);
}
public Task<EntityStorageInfoRecord> GetStorageInfoAsync()
{
return GetEntityStorageRecordAsync();
}
private async Task<EntityStorageInfoRecord> GetEntityStorageRecordAsync()
{
var record = await _entityStorageInfoRepository.FindOneAsync(_entityType);
if (record == null)
{
record = new EntityStorageInfoRecord
{
EntityType = _entityType,
DeltaStartDateTimeUtc = DateTime.UtcNow
};
record.NewId();
record.Touch();
await _entityStorageInfoRepository.InsertOneAsync(record);
}
return record;
}
}
}``` |
d0f9c2da-43ed-4a19-9032-d1282e7bbb11 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Vending.Core
{
public class VendingMachine
{
private readonly List<Coin> _coins = new List<Coin>();
private readonly List<Coin> _returnTray = new List<Coin>();
private readonly List<string> _output = new List<string>();
public IEnumerable<Coin> ReturnTray => _returnTray;
public IEnumerable<string> Output => _output;
public void Dispense(string sku)
{
_output.Add(sku);
}
public void Accept(Coin coin)
{
if (coin.Value() == 0)
{
_returnTray.Add(coin);
return;
}
_coins.Add(coin);
}
public string GetDisplayText()
{
if (!_coins.Any())
{
return "INSERT COIN";
}
return $"{CurrentTotal():C}";
}
private decimal CurrentTotal()
{
var counts = new Dictionary<Coin, int>()
{
{Coin.Nickel, 0},
{Coin.Dime, 0},
{Coin.Quarter, 0}
};
foreach (var coin in _coins)
{
counts[coin]++;
}
decimal total = 0;
foreach (var coinCount in counts)
{
total += (coinCount.Value * coinCount.Key.Value());
}
return ConvertCentsToDollars(total);
}
private static decimal ConvertCentsToDollars(decimal total)
{
return total / 100;
}
}
}
```
Revert "Added place to output products" | ```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Vending.Core
{
public class VendingMachine
{
private readonly List<Coin> _coins = new List<Coin>();
private readonly List<Coin> _returnTray = new List<Coin>();
public IEnumerable<Coin> ReturnTray => _returnTray;
public void Dispense(string soda)
{
}
public void Accept(Coin coin)
{
if (coin.Value() == 0)
{
_returnTray.Add(coin);
return;
}
_coins.Add(coin);
}
public string GetDisplayText()
{
if (!_coins.Any())
{
return "INSERT COIN";
}
return $"{CurrentTotal():C}";
}
private decimal CurrentTotal()
{
var counts = new Dictionary<Coin, int>()
{
{Coin.Nickel, 0},
{Coin.Dime, 0},
{Coin.Quarter, 0}
};
foreach (var coin in _coins)
{
counts[coin]++;
}
decimal total = 0;
foreach (var coinCount in counts)
{
total += (coinCount.Value * coinCount.Key.Value());
}
return ConvertCentsToDollars(total);
}
private static decimal ConvertCentsToDollars(decimal total)
{
return total / 100;
}
}
}
``` |
4b790446-dcec-4e6c-9fba-c64bae215efc | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
namespace MaterialDesignDemo.Converters
{
public class BrushToHexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return null;
string lowerHexString(int i) => i.ToString("X").ToLower();
var brush = (SolidColorBrush)value;
var hex = lowerHexString(brush.Color.R) +
lowerHexString(brush.Color.G) +
lowerHexString(brush.Color.B);
return "#" + hex;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
```
Fix display of color code | ```c#
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
namespace MaterialDesignDemo.Converters
{
public class BrushToHexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return null;
string lowerHexString(int i) => i.ToString("X2").ToLower();
var brush = (SolidColorBrush)value;
var hex = lowerHexString(brush.Color.R) +
lowerHexString(brush.Color.G) +
lowerHexString(brush.Color.B);
return "#" + hex;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
``` |
5216f373-0f0b-41b5-9834-22b2be349573 | {
"language": "C#"
} | ```c#
using System;
namespace RockLib.Messaging
{
/// <summary>
/// Defines an interface for receiving messages. To start receiving messages,
/// set the value of the <see cref="MessageHandler"/> property.
/// </summary>
public interface IReceiver : IDisposable
{
/// <summary>
/// Gets the name of this instance of <see cref="IReceiver"/>.
/// </summary>
string Name { get; }
/// <summary>
/// Gets or sets the message handler for this receiver. When set, the receiver is started
/// and will invoke the value's <see cref="IMessageHandler.OnMessageReceived"/> method
/// when messages are received.
/// </summary>
IMessageHandler MessageHandler { get; set; }
/// <summary>
/// Occurs when a connection is established.
/// </summary>
event EventHandler Connected;
/// <summary>
/// Occurs when a connection is lost.
/// </summary>
event EventHandler<DisconnectedEventArgs> Disconnected;
}
}```
Add remark to doc comment | ```c#
using System;
namespace RockLib.Messaging
{
/// <summary>
/// Defines an interface for receiving messages. To start receiving messages,
/// set the value of the <see cref="MessageHandler"/> property.
/// </summary>
public interface IReceiver : IDisposable
{
/// <summary>
/// Gets the name of this instance of <see cref="IReceiver"/>.
/// </summary>
string Name { get; }
/// <summary>
/// Gets or sets the message handler for this receiver. When set, the receiver is started
/// and will invoke the value's <see cref="IMessageHandler.OnMessageReceived"/> method
/// when messages are received.
/// </summary>
/// <remarks>
/// Implementions of this interface should not allow this property to be set to null or
/// to be set more than once.
/// </remarks>
IMessageHandler MessageHandler { get; set; }
/// <summary>
/// Occurs when a connection is established.
/// </summary>
event EventHandler Connected;
/// <summary>
/// Occurs when a connection is lost.
/// </summary>
event EventHandler<DisconnectedEventArgs> Disconnected;
}
}``` |
ed3bbf8c-b3ed-469b-bfa5-48280b6d5440 | {
"language": "C#"
} | ```c#
using Citysim.Map;
namespace Citysim
{
public class City
{
/// <summary>
/// Amount of cash available.
/// </summary>
public int cash = 10000; // $10,000 starting cash
/// <summary>
/// The world. Needs generation.
/// </summary>
public World world = new World();
}
}
```
Add city power and water variables. | ```c#
using Citysim.Map;
namespace Citysim
{
public class City
{
/// <summary>
/// Amount of cash available.
/// </summary>
public int cash = 10000; // $10,000 starting cash
/// <summary>
/// MW (mega watts) of electricity available to the city.
/// </summary>
public int power = 0;
/// <summary>
/// ML (mega litres) of water available to the city.
/// </summary>
public int water = 0;
/// <summary>
/// The world. Needs generation.
/// </summary>
public World world = new World();
}
}
``` |
a14fc823-c53e-4969-afc3-05c00b140571 | {
"language": "C#"
} | ```c#
// Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using System.Reflection;
namespace Nuke.Common.Utilities
{
public static class AssemblyExtensions
{
public static string GetInformationalText(this Assembly assembly)
{
return $"version {assembly.GetVersionText()} ({EnvironmentInfo.Platform}, {EnvironmentInfo.Framework})";
}
public static string GetVersionText(this Assembly assembly)
{
var informationalVersion = assembly.GetAssemblyInformationalVersion();
var plusIndex = informationalVersion.IndexOf(value: '+');
return plusIndex == -1 ? "LOCAL" : informationalVersion.Substring(startIndex: 0, length: plusIndex);
}
private static string GetAssemblyInformationalVersion(this Assembly assembly)
{
return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
}
}
}
```
Remove whitespace in informational text | ```c#
// Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using System.Reflection;
namespace Nuke.Common.Utilities
{
public static class AssemblyExtensions
{
public static string GetInformationalText(this Assembly assembly)
{
return $"version {assembly.GetVersionText()} ({EnvironmentInfo.Platform},{EnvironmentInfo.Framework})";
}
public static string GetVersionText(this Assembly assembly)
{
var informationalVersion = assembly.GetAssemblyInformationalVersion();
var plusIndex = informationalVersion.IndexOf(value: '+');
return plusIndex == -1 ? "LOCAL" : informationalVersion.Substring(startIndex: 0, length: plusIndex);
}
private static string GetAssemblyInformationalVersion(this Assembly assembly)
{
return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
}
}
}
``` |
10fab85e-d5d9-4447-9b58-5ab927af17e4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Company.WebApplication1
{
public class AzureAdB2COptions
{
public string ClientId { get; set; }
public string AzureAdB2CInstance { get; set; }
public string Tenant { get; set; }
public string SignUpSignInPolicyId { get; set; }
public string DefaultPolicy => SignUpSignInPolicyId;
public string Authority => $"{AzureAdB2CInstance}/{Tenant}/{DefaultPolicy}/v2.0";
public string Audience => ClientId;
}
}
```
Rename Tenant to Domain in the web api template | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Company.WebApplication1
{
public class AzureAdB2COptions
{
public string ClientId { get; set; }
public string AzureAdB2CInstance { get; set; }
public string Domain { get; set; }
public string SignUpSignInPolicyId { get; set; }
public string DefaultPolicy => SignUpSignInPolicyId;
public string Authority => $"{AzureAdB2CInstance}/{Domain}/{DefaultPolicy}/v2.0";
public string Audience => ClientId;
}
}
``` |
bbe9e1a9-883a-49f4-a03e-48bed9903982 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests
{
public class ClassificationsHandlerTests : AbstractLiveShareRequestHandlerTests
{
[Fact]
public async Task TestClassificationsAsync()
{
var markup =
@"class A
{
void M()
{
{|classify:var|} i = 1;
}
}";
var (solution, ranges) = CreateTestSolution(markup);
var classifyLocation = ranges["classify"].First();
var results = await TestHandleAsync<ClassificationParams, ClassificationSpan[]>(solution, CreateClassificationParams(classifyLocation));
AssertCollectionsEqual(new ClassificationSpan[] { CreateClassificationSpan("keyword", classifyLocation.Range) }, results, AssertClassificationsEqual);
}
private static void AssertClassificationsEqual(ClassificationSpan expected, ClassificationSpan actual)
{
Assert.Equal(expected.Classification, actual.Classification);
Assert.Equal(expected.Range, actual.Range);
}
private static ClassificationSpan CreateClassificationSpan(string classification, Range range)
=> new ClassificationSpan()
{
Classification = classification,
Range = range
};
private static ClassificationParams CreateClassificationParams(Location location)
=> new ClassificationParams()
{
Range = location.Range,
TextDocument = CreateTextDocumentIdentifier(location.Uri)
};
}
}
```
Fix classification test to use object type. | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests
{
public class ClassificationsHandlerTests : AbstractLiveShareRequestHandlerTests
{
[Fact]
public async Task TestClassificationsAsync()
{
var markup =
@"class A
{
void M()
{
{|classify:var|} i = 1;
}
}";
var (solution, ranges) = CreateTestSolution(markup);
var classifyLocation = ranges["classify"].First();
var results = await TestHandleAsync<ClassificationParams, object[]>(solution, CreateClassificationParams(classifyLocation));
AssertCollectionsEqual(new ClassificationSpan[] { CreateClassificationSpan("keyword", classifyLocation.Range) }, results, AssertClassificationsEqual);
}
private static void AssertClassificationsEqual(ClassificationSpan expected, ClassificationSpan actual)
{
Assert.Equal(expected.Classification, actual.Classification);
Assert.Equal(expected.Range, actual.Range);
}
private static ClassificationSpan CreateClassificationSpan(string classification, Range range)
=> new ClassificationSpan()
{
Classification = classification,
Range = range
};
private static ClassificationParams CreateClassificationParams(Location location)
=> new ClassificationParams()
{
Range = location.Range,
TextDocument = CreateTextDocumentIdentifier(location.Uri)
};
}
}
``` |
855d5e92-f434-4f72-bfb1-34f3b5100d68 | {
"language": "C#"
} | ```c#
namespace Mappy
{
using System;
using System.Windows.Forms;
using UI.Forms;
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
Application.ThreadException += Program.OnGuiUnhandedException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
private static void HandleUnhandledException(object o)
{
Exception e = o as Exception;
if (e != null)
{
throw e;
}
}
private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
HandleUnhandledException(e.Exception);
}
}
}
```
Add code to remove all old settings | ```c#
namespace Mappy
{
using System;
using System.IO;
using System.Windows.Forms;
using UI.Forms;
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
RemoveOldVersionSettings();
Application.ThreadException += Program.OnGuiUnhandedException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
private static void HandleUnhandledException(object o)
{
Exception e = o as Exception;
if (e != null)
{
throw e;
}
}
private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
HandleUnhandledException(e.Exception);
}
private static void RemoveOldVersionSettings()
{
string appDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string oldDir = Path.Combine(appDir, @"Armoured_Fish");
try
{
if (Directory.Exists(oldDir))
{
Directory.Delete(oldDir, true);
}
}
catch (IOException)
{
// we don't care if this fails
}
}
}
}
``` |
274a856a-dfcf-485a-9955-2beb00ed205d | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using DotNetCore.CAP.Models;
namespace DotNetCore.CAP
{
public abstract class CapTransactionBase : ICapTransaction
{
private readonly IDispatcher _dispatcher;
private readonly IList<CapPublishedMessage> _bufferList;
protected CapTransactionBase(IDispatcher dispatcher)
{
_dispatcher = dispatcher;
_bufferList = new List<CapPublishedMessage>(1);
}
public bool AutoCommit { get; set; }
public object DbTransaction { get; set; }
protected internal virtual void AddToSent(CapPublishedMessage msg)
{
_bufferList.Add(msg);
}
protected void Flush()
{
foreach (var message in _bufferList)
{
_dispatcher.EnqueueToPublish(message);
}
}
public abstract void Commit();
public abstract void Rollback();
public abstract void Dispose();
}
}
```
Fix flush unclaer data bugs. | ```c#
using System.Collections.Generic;
using DotNetCore.CAP.Models;
namespace DotNetCore.CAP
{
public abstract class CapTransactionBase : ICapTransaction
{
private readonly IDispatcher _dispatcher;
private readonly IList<CapPublishedMessage> _bufferList;
protected CapTransactionBase(IDispatcher dispatcher)
{
_dispatcher = dispatcher;
_bufferList = new List<CapPublishedMessage>(1);
}
public bool AutoCommit { get; set; }
public object DbTransaction { get; set; }
protected internal virtual void AddToSent(CapPublishedMessage msg)
{
_bufferList.Add(msg);
}
protected virtual void Flush()
{
foreach (var message in _bufferList)
{
_dispatcher.EnqueueToPublish(message);
}
_bufferList.Clear();
}
public abstract void Commit();
public abstract void Rollback();
public abstract void Dispose();
}
}
``` |
35e37cef-2266-4f2b-954e-df2fca35e879 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class DevicelessAudioTest : AudioThreadTest
{
public override void SetUp()
{
base.SetUp();
// lose all devices
Manager.SimulateDeviceLoss();
}
[Test]
public void TestPlayTrackWithoutDevices()
{
var track = Manager.Tracks.Get("Tracks.sample-track.mp3");
// start track
track.Restart();
Assert.IsTrue(track.IsRunning);
CheckTrackIsProgressing(track);
// stop track
track.Stop();
WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);
Assert.IsFalse(track.IsRunning);
// seek track
track.Seek(0);
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(track.CurrentTime, 0);
}
}
}
```
Fix one remaining case of incorrect audio testing | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class DevicelessAudioTest : AudioThreadTest
{
public override void SetUp()
{
base.SetUp();
// lose all devices
Manager.SimulateDeviceLoss();
}
[Test]
public void TestPlayTrackWithoutDevices()
{
var track = Manager.Tracks.Get("Tracks.sample-track.mp3");
// start track
track.Restart();
Assert.IsTrue(track.IsRunning);
CheckTrackIsProgressing(track);
// stop track
track.Stop();
WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);
Assert.IsFalse(track.IsRunning);
// seek track
track.Seek(0);
Assert.IsFalse(track.IsRunning);
WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000);
}
}
}
``` |
5ac217db-477d-4933-b0cc-35d350407b96 | {
"language": "C#"
} | ```c#
<div id="my-jumbotron" class="jumbotron">
<div class="container">
<h1>Welcome!</h1>
<p>We are Sweet Water Revolver. This is our website. Please look around and check out our...</p>
<p><a class="btn btn-primary btn-lg" role="button">... showtimes.</a></p>
</div>
</div>
```
Make the jumbotron inside a container. | ```c#
<div class="container">
<div id="my-jumbotron" class="jumbotron">
<h1>Welcome!</h1>
<p>We are Sweet Water Revolver. This is our website. Please look around and check out our...</p>
<p><a class="btn btn-primary btn-lg" role="button">... showtimes.</a></p>
</div>
</div>
``` |
906b241f-f110-44b6-a3bf-608be62a7ee2 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class test : Skill
{
private float duration = 10f;
private float expiration;
bool active;
Player player;
private int bonusStrength;
protected override void Start()
{
base.Start();
base.SetBaseValues(15, 16000, 150, "Ignite", SkillLevel.Level1);
player = GetComponent<Player>();
}
protected override void Update()
{
base.Update();
if(active && Time.time >= expiration)
{
active = false;
player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = false;
player.SetStrength(player.GetStrength() - bonusStrength);
}
}
public override void UseSkill(GameObject caller, GameObject target = null, object optionalParameters = null)
{
base.UseSkill(gameObject);
expiration = Time.time + duration;
active = true;
player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = true;
bonusStrength = player.GetIntelligence() / 2;
player.SetStrength(player.GetStrength() + bonusStrength);
}
}
public class skilltesting : MonoBehaviour {
float castInterval;
private Skill testSkill;
// Use this for initialization
void Start () {
gameObject.AddComponent<Fireball>();
testSkill = GetComponent<Skill>();
}
// Update is called once per frame
void Update () {
if(testSkill.GetCoolDownTimer() <= 0)
{
testSkill.UseSkill(gameObject);
}
}
}
```
Fix Error With Skill Test | ```c#
using UnityEngine;
using System.Collections;
public class test : Skill
{
private float duration = 10f;
private float expiration;
bool active;
Player player;
private int bonusStrength;
protected override void Start()
{
base.Start();
base.SetBaseValues(15, 16000, 150, "Ignite", SkillLevel.Level1);
player = GetComponent<Player>();
}
protected override void Update()
{
base.Update();
if(active && Time.time >= expiration)
{
active = false;
player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = false;
player.SetStrength(player.GetStrength() - bonusStrength);
}
}
public override void UseSkill(GameObject caller, GameObject target = null, object optionalParameters = null)
{
base.UseSkill(gameObject);
expiration = Time.time + duration;
active = true;
player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = true;
bonusStrength = player.GetIntelligence() / 2;
player.SetStrength(player.GetStrength() + bonusStrength);
}
}
public class skilltesting : MonoBehaviour {
float castInterval;
private Skill testSkill;
// Use this for initialization
void Start () {
gameObject.AddComponent<FireballSkill>();
testSkill = GetComponent<Skill>();
}
// Update is called once per frame
void Update () {
if(testSkill.GetCoolDownTimer() <= 0)
{
testSkill.UseSkill(gameObject);
}
}
}
``` |
049186f5-78c4-4fa7-a335-a3a6b7a2a248 | {
"language": "C#"
} | ```c#
using Xunit;
namespace Pioneer.Pagination.Tests
{
/// <summary>
/// Clamp Tests
/// </summary>
public class ClampTests
{
private readonly PaginatedMetaService _sut = new PaginatedMetaService();
[Fact]
public void LastPageDisplayed()
{
var result = _sut.GetMetaData(10, 11, 1);
Assert.True(result.NextPage.PageNumber == 10, "Expected: Last Page ");
}
[Fact]
public void FirstPageDisplayed()
{
var result = _sut.GetMetaData(10, 0, 1);
Assert.True(result.NextPage.PageNumber == 1, "Expected: First Page ");
}
}
}```
Add edge case unit tests | ```c#
using Xunit;
namespace Pioneer.Pagination.Tests
{
/// <summary>
/// Clamp Tests
/// </summary>
public class ClampTests
{
private readonly PaginatedMetaService _sut = new PaginatedMetaService();
[Fact]
public void NextPageIsLastPageInCollectionWhenRequestedPageIsGreatedThenCollection()
{
var result = _sut.GetMetaData(10, 11, 1);
Assert.True(result.NextPage.PageNumber == 10, "Expected: Last Page ");
}
[Fact]
public void PreviousPageIsLastPageMinusOneInCollectionWhenRequestedPageIsGreatedThenCollection()
{
var result = _sut.GetMetaData(10, 11, 1);
Assert.True(result.PreviousPage.PageNumber == 9, "Expected: Last Page ");
}
[Fact]
public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsZero()
{
var result = _sut.GetMetaData(10, 0, 1);
Assert.True(result.PreviousPage.PageNumber == 1, "Expected: First Page ");
}
[Fact]
public void NextPageIsSecondPageInCollectionWhenRequestedPageIsZero()
{
var result = _sut.GetMetaData(10, 0, 1);
Assert.True(result.NextPage.PageNumber == 2, "Expected: First Page ");
}
[Fact]
public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsNegative()
{
var result = _sut.GetMetaData(10, -1, 1);
Assert.True(result.PreviousPage.PageNumber == 1, "Expected: First Page ");
}
[Fact]
public void NextPageIsSecondPageInCollectionWhenRequestedPageIsNegative()
{
var result = _sut.GetMetaData(10, -1, 1);
Assert.True(result.NextPage.PageNumber == 2, "Expected: First Page ");
}
}
}``` |
c4a8fe99-2b6e-4510-83a4-85e6da33bc9e | {
"language": "C#"
} | ```c#
using TruckRouter.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
```
Enable https redirection and authorization for non-dev envs only | ```c#
using TruckRouter.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage();
}
else
{
app.UseHttpsRedirection();
app.UseAuthorization();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
``` |
41671c8c-cb1c-445a-95d4-69d07e3749f0 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Put;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Get.Users.Lists;
using TraktApiSharp.Objects.Post.Users;
[TestClass]
public class TraktUserCustomListUpdateRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListUpdateRequestIsNotAbstract()
{
typeof(TraktUserCustomListUpdateRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListUpdateRequestIsSealed()
{
typeof(TraktUserCustomListUpdateRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListUpdateRequestIsSubclassOfATraktSingleItemPutByIdRequest()
{
typeof(TraktUserCustomListUpdateRequest).IsSubclassOf(typeof(ATraktSingleItemPutByIdRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue();
}
}
}
```
Add test for authorization requirement in TraktUserCustomListUpdateRequest | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Put;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Get.Users.Lists;
using TraktApiSharp.Objects.Post.Users;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserCustomListUpdateRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListUpdateRequestIsNotAbstract()
{
typeof(TraktUserCustomListUpdateRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListUpdateRequestIsSealed()
{
typeof(TraktUserCustomListUpdateRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListUpdateRequestIsSubclassOfATraktSingleItemPutByIdRequest()
{
typeof(TraktUserCustomListUpdateRequest).IsSubclassOf(typeof(ATraktSingleItemPutByIdRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListUpdateRequestHasAuthorizationRequired()
{
var request = new TraktUserCustomListUpdateRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
``` |
c3e151c6-f12c-45d4-aa32-1ed744140542 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Umbraco.Inception.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class UmbracoTabAttribute : Attribute
{
public string Name { get; set; }
public int SortOrder { get; set; }
public UmbracoTabAttribute(string name, int sortOrder = 0)
{
Name = name;
SortOrder = sortOrder;
}
}
}
```
Add original constructor signature as there is Inception code which looks for it | ```c#
using System;
namespace Umbraco.Inception.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class UmbracoTabAttribute : Attribute
{
public string Name { get; set; }
public int SortOrder { get; set; }
public UmbracoTabAttribute(string name)
{
Name = name;
SortOrder = 0;
}
public UmbracoTabAttribute(string name, int sortOrder = 0)
{
Name = name;
SortOrder = sortOrder;
}
}
}
``` |
fd599e1a-9b48-4bce-805d-f10f258caa5e | {
"language": "C#"
} | ```c#
using System.Linq;
namespace HundredDoors
{
public static class HundredDoors
{
/// <summary>
/// Solves the 100 Doors problem
/// </summary>
/// <returns>An array with 101 values, each representing a door (except 0). True = open</returns>
public static bool[] Solve()
{
// Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it
bool[] doors = Enumerable.Repeat(false, 101).ToArray();
// We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door
for (int pass = 1; pass <= 100; pass++)
for (int i = pass; i < doors.Length; i += pass)
doors[i] = !doors[i];
return doors;
}
}
}
```
Revert "Revert "Added "final door count" comment at return value."" | ```c#
using System.Linq;
namespace HundredDoors
{
public static class HundredDoors
{
/// <summary>
/// Solves the 100 Doors problem
/// </summary>
/// <returns>An array with 101 values, each representing a door (except 0). True = open</returns>
public static bool[] Solve()
{
// Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it
bool[] doors = Enumerable.Repeat(false, 101).ToArray();
// We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door
for (int pass = 1; pass <= 100; pass++)
for (int i = pass; i < doors.Length; i += pass)
doors[i] = !doors[i];
return doors; //final door count
}
}
}
``` |
16922b48-8e87-4b4f-a059-0d720f20f9f4 | {
"language": "C#"
} | ```c#
using Cake.Core;
using Cake.Core.Annotations;
using System;
namespace Cake.Docker
{
partial class DockerAliases
{
/// <summary>
/// Logs <paramref name="container"/> using default settings.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="container">The list of containers.</param>
[CakeMethodAlias]
public static void DockerLogs(this ICakeContext context, string container)
{
DockerLogs(context, new DockerContainerLogsSettings(), container);
}
/// <summary>
/// Logs <paramref name="container"/> using the given <paramref name="settings"/>.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="container">The list of containers.</param>
/// <param name="settings">The settings.</param>
[CakeMethodAlias]
public static void DockerLogs(this ICakeContext context, DockerContainerLogsSettings settings, string container)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (container == null)
{
throw new ArgumentNullException("container");
}
var runner = new GenericDockerRunner<DockerContainerLogsSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
runner.Run("start", settings ?? new DockerContainerLogsSettings(), new string[] { container });
}
}
}
```
Fix log command and return log lines | ```c#
using Cake.Core;
using Cake.Core.Annotations;
using System;
using System.Linq;
using System.Collections.Generic;
namespace Cake.Docker
{
partial class DockerAliases
{
/// <summary>
/// Logs <paramref name="container"/> using default settings.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="container">The list of containers.</param>
[CakeMethodAlias]
public static IEnumerable<string> DockerLogs(this ICakeContext context, string container)
{
return DockerLogs(context, new DockerContainerLogsSettings(), container);
}
/// <summary>
/// Logs <paramref name="container"/> using the given <paramref name="settings"/>.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="container">The list of containers.</param>
/// <param name="settings">The settings.</param>
[CakeMethodAlias]
public static IEnumerable<string> DockerLogs(this ICakeContext context, DockerContainerLogsSettings settings, string container)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (container == null)
{
throw new ArgumentNullException("container");
}
var runner = new GenericDockerRunner<DockerContainerLogsSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
return runner.RunWithResult("logs", settings ?? new DockerContainerLogsSettings(), r => r.ToArray(), new string[] { container });
}
}
}
``` |
20c4c4b5-1958-468a-8117-ab4fce5462fc | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Bonobo.Git.Server.Controllers;
using Bonobo.Git.Server.Test.Integration.Web;
using Bonobo.Git.Server.Test.IntegrationTests.Helpers;
using SpecsFor.Mvc;
namespace Bonobo.Git.Server.Test.IntegrationTests
{
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium;
[TestClass]
public class SharedLayoutTests : IntegrationTestBase
{
[TestMethod, TestCategory(TestCategories.WebIntegrationTest)]
public void DropdownNavigationWorks()
{
var reponame = "A_Nice_Repo";
var id1 = ITH.CreateRepositoryOnWebInterface(reponame);
var id2 = ITH.CreateRepositoryOnWebInterface("other_name");
app.NavigateTo<RepositoryController>(c => c.Detail(id2));
var element = app.Browser.FindElementByCssSelector("select#Repositories");
var dropdown = new SelectElement(element);
dropdown.SelectByText(reponame);
app.UrlMapsTo<RepositoryController>(c => c.Detail(id1));
app.WaitForElementToBeVisible(By.CssSelector("select#Repositories"), TimeSpan.FromSeconds(10));
dropdown = new SelectElement(app.Browser.FindElementByCssSelector("select#Repositories"));
dropdown.SelectByText("other_name");
app.UrlMapsTo<RepositoryController>(c => c.Detail(id2));
}
}
}
```
Make DropdDownNavigationWorks more reliable and use new test methods. | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Bonobo.Git.Server.Controllers;
using Bonobo.Git.Server.Test.Integration.Web;
using Bonobo.Git.Server.Test.IntegrationTests.Helpers;
using SpecsFor.Mvc;
namespace Bonobo.Git.Server.Test.IntegrationTests
{
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium;
using System.Threading;
[TestClass]
public class SharedLayoutTests : IntegrationTestBase
{
[TestMethod, TestCategory(TestCategories.WebIntegrationTest)]
public void DropdownNavigationWorks()
{
var reponame = ITH.MakeName();
var otherreponame = ITH.MakeName(reponame + "_other");
var repoId = ITH.CreateRepositoryOnWebInterface(reponame);
var otherrepoId = ITH.CreateRepositoryOnWebInterface(otherreponame);
app.NavigateTo<RepositoryController>(c => c.Detail(otherrepoId));
var element = app.Browser.FindElementByCssSelector("select#Repositories");
var dropdown = new SelectElement(element);
dropdown.SelectByText(reponame);
Thread.Sleep(2000);
app.UrlMapsTo<RepositoryController>(c => c.Detail(repoId));
app.WaitForElementToBeVisible(By.CssSelector("select#Repositories"), TimeSpan.FromSeconds(10));
dropdown = new SelectElement(app.Browser.FindElementByCssSelector("select#Repositories"));
dropdown.SelectByText(otherreponame);
Thread.Sleep(2000);
app.UrlMapsTo<RepositoryController>(c => c.Detail(otherrepoId));
}
}
}
``` |
d598b54f-6ccc-490b-8601-2a85b6d597e5 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions;
namespace PSql.Tests
{
using static ScriptExecutor;
internal static class StringExtensions
{
internal static void
ShouldOutput(
this string script,
params object[] expected
)
{
if (script is null)
throw new ArgumentNullException(nameof(script));
if (expected is null)
throw new ArgumentNullException(nameof(expected));
var (objects, exception) = Execute(script);
exception.Should().BeNull();
objects.Should().HaveCount(expected.Length);
objects
.Select(o => o?.BaseObject)
.Should().BeEquivalentTo(expected, x => x.IgnoringCyclicReferences());
}
internal static void
ShouldThrow<T>(
this string script,
string messagePart
)
where T : Exception
{
script.ShouldThrow<T>(
e => e.Message.Contains(messagePart, StringComparison.OrdinalIgnoreCase)
);
}
internal static void
ShouldThrow<T>(
this string script,
Expression<Func<T, bool>>? predicate = null
)
where T : Exception
{
if (script is null)
throw new ArgumentNullException(nameof(script));
var (_, exception) = Execute(script);
exception.Should().NotBeNull().And.BeAssignableTo<T>();
if (predicate is not null)
exception.Should().Match<T>(predicate);
}
}
}
```
Rework exception asserts to improve failure messages. | ```c#
using System;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions;
namespace PSql.Tests
{
using static ScriptExecutor;
internal static class StringExtensions
{
internal static void
ShouldOutput(
this string script,
params object[] expected
)
{
if (script is null)
throw new ArgumentNullException(nameof(script));
if (expected is null)
throw new ArgumentNullException(nameof(expected));
var (objects, exception) = Execute(script);
exception.Should().BeNull();
objects.Should().HaveCount(expected.Length);
objects
.Select(o => o?.BaseObject)
.Should().BeEquivalentTo(expected, x => x.IgnoringCyclicReferences());
}
internal static void
ShouldThrow<T>(this string script, string messagePart)
where T : Exception
{
var exception = script.ShouldThrow<T>();
exception.Message.Should().Contain(messagePart);
}
internal static T ShouldThrow<T>(this string script)
where T : Exception
{
if (script is null)
throw new ArgumentNullException(nameof(script));
var (_, exception) = Execute(script);
return exception
.Should().NotBeNull()
.And .BeAssignableTo<T>()
.Subject;
}
}
}
``` |
48515917-119e-4145-81e7-fd69b7077fbc | {
"language": "C#"
} | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Renci.SshNet.Security.Cryptography;
using Renci.SshNet.Tests.Common;
using System;
namespace Renci.SshNet.Tests.Classes
{
/// <summary>
/// Holds information about key size and cipher to use
/// </summary>
[TestClass]
public class CipherInfoTest : TestBase
{
/// <summary>
///A test for CipherInfo Constructor
///</summary>
[TestMethod()]
public void CipherInfoConstructorTest()
{
int keySize = 0; // TODO: Initialize to an appropriate value
Func<byte[], byte[], BlockCipher> cipher = null; // TODO: Initialize to an appropriate value
CipherInfo target = new CipherInfo(keySize, cipher);
Assert.Inconclusive("TODO: Implement code to verify target");
}
}
}```
Fix build when targeting .NET Framework 3.5 as Func only supports covariance on .NET Framework 4.0 and higher. | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Renci.SshNet.Security.Cryptography;
using Renci.SshNet.Tests.Common;
using System;
namespace Renci.SshNet.Tests.Classes
{
/// <summary>
/// Holds information about key size and cipher to use
/// </summary>
[TestClass]
public class CipherInfoTest : TestBase
{
/// <summary>
///A test for CipherInfo Constructor
///</summary>
[TestMethod()]
public void CipherInfoConstructorTest()
{
int keySize = 0; // TODO: Initialize to an appropriate value
Func<byte[], byte[], Cipher> cipher = null; // TODO: Initialize to an appropriate value
CipherInfo target = new CipherInfo(keySize, cipher);
Assert.Inconclusive("TODO: Implement code to verify target");
}
}
}``` |
49e6cdf0-2b3f-4b9e-9206-e5fd417f71ae | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Indicates that the implementing type can be serialized via <see cref="ToString"/>
/// for diagnostic message purposes.
/// </summary>
/// <remarks>
/// Not appropriate on types that require localization, since localization should
/// happen after serialization.
/// </remarks>
internal interface IMessageSerializable
{
}
}
```
Fix a warning about a cref in an XML doc comment. | ```c#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Indicates that the implementing type can be serialized via <see cref="object.ToString"/>
/// for diagnostic message purposes.
/// </summary>
/// <remarks>
/// Not appropriate on types that require localization, since localization should
/// happen after serialization.
/// </remarks>
internal interface IMessageSerializable
{
}
}
``` |
05434fb0-d458-4139-983a-38f516e0c2ff | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public interface IRepository<TEntity, TPk>
where TEntity : class, IEntity<TPk>
{
TEntity Get(TPk key, ISession session = null);
Task<TEntity> GetAsync(TPk key, ISession session = null);
IEnumerable<TEntity> GetAll(ISession session = null);
Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null);
TPk SaveOrUpdate(TEntity entity, IUnitOfWork transaction);
Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork transaction);
}
}```
Change get method and add the new getter | ```c#
using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public interface IRepository<TEntity, TPk>
where TEntity : class, IEntity<TPk>
{
TEntity GetKey(TPk key, ISession session = null);
Task<TEntity> GetKeyAsync(TPk key, ISession session = null);
TEntity Get(TEntity entity, ISession session = null);
Task<TEntity> GetAsync(TEntity entity, ISession session = null)
IEnumerable<TEntity> GetAll(ISession session = null);
Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null);
TPk SaveOrUpdate(TEntity entity, IUnitOfWork transaction);
Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork transaction);
}
}``` |
c0737f95-ddbb-4949-9c3f-3c67d5f9ab96 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.Linq;
namespace mountain_thoughts
{
public class Program
{
public static void Main(string[] args)
{
Process mountainProcess = NativeMethods.GetMountainProcess();
if (mountainProcess == null)
{
Console.WriteLine("Could not get process. Is Mountain running?");
Console.ReadLine();
Environment.Exit(1);
}
IntPtr handle = mountainProcess.Handle;
IntPtr address = NativeMethods.GetStringAddress(mountainProcess);
Twitter.Authenticate();
NativeMethods.StartReadingString(handle, address, Callback);
Console.ReadLine();
NativeMethods.StopReadingString();
}
private static void Callback(string thought)
{
string properThought = string.Empty;
foreach (string word in thought.Split(' ').Skip(1))
{
string lowerWord = word;
if (word != "I")
lowerWord = word.ToLowerInvariant();
properThought += lowerWord + " ";
}
properThought = properThought.Trim();
Console.WriteLine(properThought);
Twitter.Tweet(string.Format("\"{0}\"", properThought));
}
}
}```
Revert "Exclude the first word" | ```c#
using System;
using System.Diagnostics;
namespace mountain_thoughts
{
public class Program
{
public static void Main(string[] args)
{
Process mountainProcess = NativeMethods.GetMountainProcess();
if (mountainProcess == null)
{
Console.WriteLine("Could not get process. Is Mountain running?");
Console.ReadLine();
Environment.Exit(1);
}
IntPtr handle = mountainProcess.Handle;
IntPtr address = NativeMethods.GetStringAddress(mountainProcess);
Twitter.Authenticate();
NativeMethods.StartReadingString(handle, address, Callback);
Console.ReadLine();
NativeMethods.StopReadingString();
}
private static void Callback(string thought)
{
string properThought = string.Empty;
foreach (string word in thought.Split(' '))
{
string lowerWord = word;
if (word != "I")
lowerWord = word.ToLowerInvariant();
properThought += lowerWord + " ";
}
properThought = properThought.Trim();
Console.WriteLine(properThought);
Twitter.Tweet(string.Format("\"{0}\"", properThought));
}
}
}``` |
040095e3-4c4c-4fab-bf5e-04883ea0dc17 | {
"language": "C#"
} | ```c#
//-----------------------------------------------------------------------
// <copyright file="AllScoreData.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
#pragma warning disable SA1600 // Elements should be documented
using System.Collections.Generic;
namespace ThScoreFileConverter.Models.Th165
{
internal class AllScoreData
{
private readonly List<IScore> scores;
public AllScoreData() => this.scores = new List<IScore>(Definitions.SpellCards.Count);
public Th095.HeaderBase Header { get; private set; }
public IReadOnlyList<IScore> Scores => this.scores;
public IStatus Status { get; private set; }
public void Set(Th095.HeaderBase header) => this.Header = header;
public void Set(IScore score) => this.scores.Add(score);
public void Set(IStatus status) => this.Status = status;
}
}
```
Fix not to use expression-bodied constructors (cont.) | ```c#
//-----------------------------------------------------------------------
// <copyright file="AllScoreData.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
#pragma warning disable SA1600 // Elements should be documented
using System.Collections.Generic;
namespace ThScoreFileConverter.Models.Th165
{
internal class AllScoreData
{
private readonly List<IScore> scores;
public AllScoreData()
{
this.scores = new List<IScore>(Definitions.SpellCards.Count);
}
public Th095.HeaderBase Header { get; private set; }
public IReadOnlyList<IScore> Scores => this.scores;
public IStatus Status { get; private set; }
public void Set(Th095.HeaderBase header) => this.Header = header;
public void Set(IScore score) => this.scores.Add(score);
public void Set(IStatus status) => this.Status = status;
}
}
``` |
cf7dca4a-b06f-4ccf-9d0c-5c071045f241 | {
"language": "C#"
} | ```c#
namespace MultiMiner.Win.Extensions
{
static class TimeIntervalExtensions
{
public static int ToMinutes(this MultiMiner.Win.ApplicationConfiguration.TimerInterval timerInterval)
{
int coinStatsMinutes;
switch (timerInterval)
{
case ApplicationConfiguration.TimerInterval.FiveMinutes:
coinStatsMinutes = 5;
break;
case ApplicationConfiguration.TimerInterval.ThirtyMinutes:
coinStatsMinutes = 30;
break;
case ApplicationConfiguration.TimerInterval.OneHour:
coinStatsMinutes = 1 * 60;
break;
case ApplicationConfiguration.TimerInterval.ThreeHours:
coinStatsMinutes = 3 * 60;
break;
case ApplicationConfiguration.TimerInterval.SixHours:
coinStatsMinutes = 6 * 60;
break;
case ApplicationConfiguration.TimerInterval.TwelveHours:
coinStatsMinutes = 12 * 60;
break;
default:
coinStatsMinutes = 15;
break;
}
return coinStatsMinutes;
}
}
}
```
Handle the TwoHour time interval for strategies - was defaulting to 15 | ```c#
namespace MultiMiner.Win.Extensions
{
static class TimeIntervalExtensions
{
public static int ToMinutes(this MultiMiner.Win.ApplicationConfiguration.TimerInterval timerInterval)
{
int coinStatsMinutes;
switch (timerInterval)
{
case ApplicationConfiguration.TimerInterval.FiveMinutes:
coinStatsMinutes = 5;
break;
case ApplicationConfiguration.TimerInterval.ThirtyMinutes:
coinStatsMinutes = 30;
break;
case ApplicationConfiguration.TimerInterval.OneHour:
coinStatsMinutes = 1 * 60;
break;
case ApplicationConfiguration.TimerInterval.TwoHours:
coinStatsMinutes = 2 * 60;
break;
case ApplicationConfiguration.TimerInterval.ThreeHours:
coinStatsMinutes = 3 * 60;
break;
case ApplicationConfiguration.TimerInterval.SixHours:
coinStatsMinutes = 6 * 60;
break;
case ApplicationConfiguration.TimerInterval.TwelveHours:
coinStatsMinutes = 12 * 60;
break;
default:
coinStatsMinutes = 15;
break;
}
return coinStatsMinutes;
}
}
}
``` |
6c3bf274-1b75-42ce-8320-ebfa4d7d7dc3 | {
"language": "C#"
} | ```c#
using System;
namespace Csla.Serialization.Mobile
{
/// <summary>
/// Placeholder for null child objects.
/// </summary>
[Serializable()]
public sealed class NullPlaceholder : IMobileObject
{
#region Constructors
public NullPlaceholder()
{
// Nothing
}
#endregion
#region IMobileObject Members
public void GetState(SerializationInfo info)
{
// Nothing
}
public void GetChildren(SerializationInfo info, MobileFormatter formatter)
{
// Nothing
}
public void SetState(SerializationInfo info)
{
// Nothing
}
public void SetChildren(SerializationInfo info, MobileFormatter formatter)
{
// Nothing
}
#endregion
}
}
```
Add missing XML docs to code. bugid: 272 | ```c#
using System;
namespace Csla.Serialization.Mobile
{
/// <summary>
/// Placeholder for null child objects.
/// </summary>
[Serializable()]
public sealed class NullPlaceholder : IMobileObject
{
#region Constructors
/// <summary>
/// Creates an instance of the type.
/// </summary>
public NullPlaceholder()
{
// Nothing
}
#endregion
#region IMobileObject Members
/// <summary>
/// Method called by MobileFormatter when an object
/// should serialize its data. The data should be
/// serialized into the SerializationInfo parameter.
/// </summary>
/// <param name="info">
/// Object to contain the serialized data.
/// </param>
public void GetState(SerializationInfo info)
{
// Nothing
}
/// <summary>
/// Method called by MobileFormatter when an object
/// should serialize its child references. The data should be
/// serialized into the SerializationInfo parameter.
/// </summary>
/// <param name="info">
/// Object to contain the serialized data.
/// </param>
/// <param name="formatter">
/// Reference to the formatter performing the serialization.
/// </param>
public void GetChildren(SerializationInfo info, MobileFormatter formatter)
{
// Nothing
}
/// <summary>
/// Method called by MobileFormatter when an object
/// should be deserialized. The data should be
/// deserialized from the SerializationInfo parameter.
/// </summary>
/// <param name="info">
/// Object containing the serialized data.
/// </param>
public void SetState(SerializationInfo info)
{
// Nothing
}
/// <summary>
/// Method called by MobileFormatter when an object
/// should deserialize its child references. The data should be
/// deserialized from the SerializationInfo parameter.
/// </summary>
/// <param name="info">
/// Object containing the serialized data.
/// </param>
/// <param name="formatter">
/// Reference to the formatter performing the deserialization.
/// </param>
public void SetChildren(SerializationInfo info, MobileFormatter formatter)
{
// Nothing
}
#endregion
}
}
``` |
cdb389d3-2066-4821-9ce2-b2b15b13edf7 | {
"language": "C#"
} | ```c#
// Copyright (c) ComUnity 2015
// Hans Malherbe <hansm@comunity.co.za>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace CEP
{
public class UserProfile
{
[Key, Required, StringLength(10, MinimumLength = 10, ErrorMessage = "Mobile number must be exactly 10 digits")]
public string Cell { get; set; }
[StringLength(50)]
public string Name { get; set; }
[StringLength(50)]
public string Surname { get; set; }
[StringLength(100)]
public string HouseNumberAndStreetName { get; set; }
[StringLength(10)]
public string PostalCode { get; set; }
[StringLength(50)]
public string Province { get; set; }
[StringLength(100)]
public string Picture { get; set; }
[StringLength(10)]
public string HomePhone { get; set; }
[StringLength(10)]
public string WorkPhone { get; set; }
[StringLength(350)]
public string Email { get; set; }
[StringLength(13)]
public string IdNumber { get; set; }
[StringLength(100)]
public string CrmContactId { get; set; }
public virtual ICollection<Feedback> Feedbacks { get; set; }
public virtual ICollection<FaultLog> Faults { get; set; }
}
}```
Change user picture field to PictureUrl | ```c#
// Copyright (c) ComUnity 2015
// Hans Malherbe <hansm@comunity.co.za>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace CEP
{
public class UserProfile
{
[Key, Required, StringLength(10, MinimumLength = 10, ErrorMessage = "Mobile number must be exactly 10 digits")]
public string Cell { get; set; }
[StringLength(50)]
public string Name { get; set; }
[StringLength(50)]
public string Surname { get; set; }
[StringLength(100)]
public string HouseNumberAndStreetName { get; set; }
[StringLength(10)]
public string PostalCode { get; set; }
[StringLength(50)]
public string Province { get; set; }
[StringLength(2000)]
public string PictureUrl { get; set; }
[StringLength(10)]
public string HomePhone { get; set; }
[StringLength(10)]
public string WorkPhone { get; set; }
[StringLength(350)]
public string Email { get; set; }
[StringLength(13)]
public string IdNumber { get; set; }
[StringLength(100)]
public string CrmContactId { get; set; }
public virtual ICollection<Feedback> Feedbacks { get; set; }
public virtual ICollection<FaultLog> Faults { get; set; }
}
}``` |
a9ea1419-304a-48da-aeab-f09f7ae2b36f | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Ganss.Text
{
/// <summary>
/// Provides extension methods.
/// </summary>
public static class Extensions
{
/// <summary>
/// Determines whether this instance contains the specified words.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="words">The words.</param>
/// <returns>The matched words.</returns>
public static IEnumerable<WordMatch> Contains(this string text, IEnumerable<string> words)
{
return new AhoCorasick(words).Search(text);
}
/// <summary>
/// Determines whether this instance contains the specified words.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="words">The words.</param>
/// <returns>The matched words.</returns>
public static IEnumerable<WordMatch> Contains(this string text, params string[] words)
{
return new AhoCorasick(words).Search(text);
}
}
}
```
Add custom char comparison to extension methods | ```c#
using System.Collections.Generic;
namespace Ganss.Text
{
/// <summary>
/// Provides extension methods.
/// </summary>
public static class Extensions
{
/// <summary>
/// Determines whether this instance contains the specified words.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="words">The words.</param>
/// <returns>The matched words.</returns>
public static IEnumerable<WordMatch> Contains(this string text, IEnumerable<string> words)
{
return new AhoCorasick(words).Search(text);
}
/// <summary>
/// Determines whether this instance contains the specified words.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="words">The words.</param>
/// <returns>The matched words.</returns>
public static IEnumerable<WordMatch> Contains(this string text, params string[] words)
{
return new AhoCorasick(words).Search(text);
}
/// <summary>
/// Determines whether this instance contains the specified words.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="comparer">The comparer used to compare individual characters.</param>
/// <param name="words">The words.</param>
/// <returns>The matched words.</returns>
public static IEnumerable<WordMatch> Contains(this string text, IEqualityComparer<char> comparer, IEnumerable<string> words)
{
return new AhoCorasick(comparer, words).Search(text);
}
/// <summary>
/// Determines whether this instance contains the specified words.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="comparer">The comparer used to compare individual characters.</param>
/// <param name="words">The words.</param>
/// <returns>The matched words.</returns>
public static IEnumerable<WordMatch> Contains(this string text, IEqualityComparer<char> comparer, params string[] words)
{
return new AhoCorasick(comparer, words).Search(text);
}
}
}
``` |
478f37ff-3d1c-41b3-9d72-9b22c521502e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Event;
using Serilog.Events;
using Serilog.Parsing;
namespace Akka.Serilog.Event.Serilog
{
public class SerilogLogMessageFormatter : ILogMessageFormatter
{
private readonly MessageTemplateCache _templateCache;
public SerilogLogMessageFormatter()
{
_templateCache = new MessageTemplateCache(new MessageTemplateParser());
}
public string Format(string format, params object[] args)
{
var template = _templateCache.Parse(format);
var propertyTokens = template.Tokens.OfType<PropertyToken>().ToArray();
var properties = new Dictionary<string, LogEventPropertyValue>();
if (propertyTokens.Length != args.Length)
throw new FormatException("Invalid number or arguments provided.");
for (var i = 0; i < propertyTokens.Length; i++)
{
var arg = args[i];
properties.Add(propertyTokens[i].PropertyName, new ScalarValue(arg));
}
return template.Render(properties);
}
}
}```
Change the way we match args to property tokens to more closely match Serilog when you pass in too few or too many arguments | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Event;
using Serilog.Events;
using Serilog.Parsing;
namespace Akka.Serilog.Event.Serilog
{
public class SerilogLogMessageFormatter : ILogMessageFormatter
{
private readonly MessageTemplateCache _templateCache;
public SerilogLogMessageFormatter()
{
_templateCache = new MessageTemplateCache(new MessageTemplateParser());
}
public string Format(string format, params object[] args)
{
var template = _templateCache.Parse(format);
var propertyTokens = template.Tokens.OfType<PropertyToken>().ToArray();
var properties = new Dictionary<string, LogEventPropertyValue>();
for (var i = 0; i < args.Length; i++)
{
var propertyToken = propertyTokens.ElementAtOrDefault(i);
if (propertyToken == null)
break;
properties.Add(propertyToken.PropertyName, new ScalarValue(args[i]));
}
return template.Render(properties);
}
}
}``` |
f7600525-03cd-4a44-97fb-4ae04362fe4c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace RockyTV.Duality.Plugins.IronPython
{
public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
[DontSerialize]
private PythonExecutionEngine _engine;
protected PythonExecutionEngine Engine
{
get { return _engine; }
}
public void OnInit(InitContext context)
{
if (!Script.IsAvailable) return;
_engine = new PythonExecutionEngine(Script.Res.Content);
_engine.SetVariable("gameObject", GameObj);
if (_engine.HasMethod("start"))
_engine.CallMethod("start");
}
public void OnUpdate()
{
if (_engine.HasMethod("update"))
_engine.CallMethod("update");
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
```
Call 'update' with Delta time | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace RockyTV.Duality.Plugins.IronPython
{
public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
[DontSerialize]
private PythonExecutionEngine _engine;
protected PythonExecutionEngine Engine
{
get { return _engine; }
}
protected virtual float Delta
{
get { return Time.MsPFMult * Time.TimeMult; }
}
public void OnInit(InitContext context)
{
if (!Script.IsAvailable) return;
_engine = new PythonExecutionEngine(Script.Res.Content);
_engine.SetVariable("gameObject", GameObj);
if (_engine.HasMethod("start"))
_engine.CallMethod("start");
}
public void OnUpdate()
{
if (_engine.HasMethod("update"))
_engine.CallMethod("update", Delta);
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
``` |
2f2cabdf-a666-4d28-91f3-e780c384aa92 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Reflection;
[assembly: AssemblyVersion("1.0.0.*")]
public class Loader : MonoBehaviour
{
/// <summary>
/// DebugUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _debugUI;
/// <summary>
/// ModalDialog prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _modalDialog;
/// <summary>
/// MainMenu prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _mainMenu;
/// <summary>
/// InGameUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _inGameUI;
/// <summary>
/// SoundManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _soundManager;
/// <summary>
/// GameManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _gameManager;
protected void Awake()
{
// Check if the instances have already been assigned to static variables or they are still null.
if (DebugUI.Instance == null)
{
Instantiate(_debugUI);
}
if (ModalDialog.Instance == null)
{
Instantiate(_modalDialog);
}
if (MainMenu.Instance == null)
{
Instantiate(_mainMenu);
}
if (InGameUI.Instance == null)
{
Instantiate(_inGameUI);
}
if (SoundManager.Instance == null)
{
Instantiate(_soundManager);
}
if (GameManager.Instance == null)
{
Instantiate(_gameManager);
}
}
}
```
Change version up to 1.1.0 | ```c#
using UnityEngine;
using System.Reflection;
[assembly: AssemblyVersion("1.1.0.*")]
public class Loader : MonoBehaviour
{
/// <summary>
/// DebugUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _debugUI;
/// <summary>
/// ModalDialog prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _modalDialog;
/// <summary>
/// MainMenu prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _mainMenu;
/// <summary>
/// InGameUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _inGameUI;
/// <summary>
/// SoundManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _soundManager;
/// <summary>
/// GameManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _gameManager;
protected void Awake()
{
// Check if the instances have already been assigned to static variables or they are still null.
if (DebugUI.Instance == null)
{
Instantiate(_debugUI);
}
if (ModalDialog.Instance == null)
{
Instantiate(_modalDialog);
}
if (MainMenu.Instance == null)
{
Instantiate(_mainMenu);
}
if (InGameUI.Instance == null)
{
Instantiate(_inGameUI);
}
if (SoundManager.Instance == null)
{
Instantiate(_soundManager);
}
if (GameManager.Instance == null)
{
Instantiate(_gameManager);
}
}
}
``` |
420c4981-5bd5-466d-99a8-5cc6b89c1d64 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Console;
namespace ConsoleApp
{
public class Table
{
private readonly string tableName;
private readonly IEnumerable<Column> columns;
public Table(string tableName, IEnumerable<Column> columns)
{
this.tableName = tableName;
this.columns = columns;
}
public void OutputMigrationCode(TextWriter writer)
{
writer.Write(@"namespace Cucu
{
[Migration(");
writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss"));
writer.Write(@")]
public class Vaca : Migration
{
public override void Up()
{
Create.Table(""");
writer.Write(tableName);
writer.Write(@""")");
columns.ToList().ForEach(c =>
{
writer.WriteLine();
writer.Write(c.FluentMigratorCode());
});
writer.WriteLine(@";
}
public override void Down()
{
// nothing here yet
}
}
}");
}
}
class Program
{
private static void Main()
{
var columnsProvider = new ColumnsProvider(@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;");
var tableName = "Book";
var columns = columnsProvider.GetColumnsAsync("dbo", tableName).GetAwaiter().GetResult();
new Table(tableName, columns).OutputMigrationCode(Out);
}
}
}
```
Put variables in Main first | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Console;
namespace ConsoleApp
{
public class Table
{
private readonly string tableName;
private readonly IEnumerable<Column> columns;
public Table(string tableName, IEnumerable<Column> columns)
{
this.tableName = tableName;
this.columns = columns;
}
public void OutputMigrationCode(TextWriter writer)
{
writer.Write(@"namespace Cucu
{
[Migration(");
writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss"));
writer.Write(@")]
public class Vaca : Migration
{
public override void Up()
{
Create.Table(""");
writer.Write(tableName);
writer.Write(@""")");
columns.ToList().ForEach(c =>
{
writer.WriteLine();
writer.Write(c.FluentMigratorCode());
});
writer.WriteLine(@";
}
public override void Down()
{
// nothing here yet
}
}
}");
}
}
class Program
{
private static void Main()
{
var connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;";
var schemaName = "dbo";
var tableName = "Book";
var columnsProvider = new ColumnsProvider(connectionString);
var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult();
new Table(tableName, columns).OutputMigrationCode(Out);
}
}
}
``` |
4fb06a43-7e74-4541-ac33-521fdb58a92a | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using TMPro;
#if LEAPMOTIONCORE_PRESENT
using Microsoft.MixedReality.Toolkit.LeapMotion.Input;
#endif
namespace Microsoft.MixedReality.Toolkit.Examples
{
/// <summary>
/// Returns the orientation of Leap Motion Controller
/// </summary>
public class LeapMotionOrientationDisplay : MonoBehaviour
{
#if LEAPMOTIONCORE_PRESENT
[SerializeField]
private TextMeshProUGUI orientationText;
private LeapMotionDeviceManagerProfile managerProfile;
private void Start()
{
if (GetLeapManager())
{
orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString();
}
else
{
orientationText.text = "Orientation: Unavailable";
}
}
private LeapMotionDeviceManagerProfile GetLeapManager()
{
if (!MixedRealityToolkit.Instance.ActiveProfile)
{
return null;
}
foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations)
{
if (config.ComponentType == typeof(LeapMotionDeviceManager))
{
managerProfile = (LeapMotionDeviceManagerProfile)config.Profile;
return managerProfile;
}
}
return null;
}
#endif
}
}
```
Add standalone ifdef to leap example scene script | ```c#
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using TMPro;
#if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE
using Microsoft.MixedReality.Toolkit.LeapMotion.Input;
#endif
namespace Microsoft.MixedReality.Toolkit.Examples
{
/// <summary>
/// Returns the orientation of Leap Motion Controller
/// </summary>
public class LeapMotionOrientationDisplay : MonoBehaviour
{
#if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE
[SerializeField]
private TextMeshProUGUI orientationText;
private LeapMotionDeviceManagerProfile managerProfile;
private void Start()
{
if (GetLeapManager())
{
orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString();
}
else
{
orientationText.text = "Orientation: Unavailable";
}
}
private LeapMotionDeviceManagerProfile GetLeapManager()
{
if (!MixedRealityToolkit.Instance.ActiveProfile)
{
return null;
}
foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations)
{
if (config.ComponentType == typeof(LeapMotionDeviceManager))
{
managerProfile = (LeapMotionDeviceManagerProfile)config.Profile;
return managerProfile;
}
}
return null;
}
#endif
}
}
``` |
94cd8bf9-2f72-419b-8306-81355b664cb6 | {
"language": "C#"
} | ```c#
// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SmugMugCodeGen
{
public static class Constants
{
public const string PropertyDefinition = @"public {0} {1} {{get; set;}}";
public const string EnumDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SmugMug.v2.Types
{{
public enum {0}
{{
{1}
}}
}}
";
public const string ClassDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace SmugMug.v2.Types
{{
public partial class {0}Entity
{{
{1}
}}
}}
";
}
}
```
Make sure that classes generated derive from a common type to allow code sharing | ```c#
// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SmugMugCodeGen
{
public static class Constants
{
public const string PropertyDefinition = @"public {0} {1} {{get; set;}}";
public const string EnumDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SmugMug.v2.Types
{{
public enum {0}
{{
{1}
}}
}}
";
public const string ClassDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace SmugMug.v2.Types
{{
public partial class {0}Entity : SmugMugEntity
{{
{1}
}}
}}
";
}
}
``` |
a0f381dd-6aa7-4822-ba5f-6d6b06e9b183 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Levels : MonoBehaviour
{
/* Cette classe a pour destin d'être sur un prefab.
* Ce prefab agira comme une config manuelle de niveaux pour faciliter le level design.
* On pourra faire différentes configs si on veut (mettons une par difficulté) et ultimement glisser cette config dans le gamecontroller
* pour qu'il s'en serve.
* */
[SerializeField] WorkDay[] days;
int currentLevel = 0;
public void StartNext()
{
//starts next level
}
public void EndCurrent()
{
//ends current level
currentLevel++;
if (days[currentLevel].AddsJob)
{
// add a job to pool
}
}
}
```
Add max job count to levels | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Levels : MonoBehaviour
{
/* Cette classe a pour destin d'être sur un prefab.
* Ce prefab agira comme une config manuelle de niveaux pour faciliter le level design.
* On pourra faire différentes configs si on veut (mettons une par difficulté) et ultimement glisser cette config dans le gamecontroller
* pour qu'il s'en serve.
* */
[SerializeField] WorkDay[] days;
[SerializeField] int maxJobCount;
int currentLevel = 0;
public void StartNext()
{
//starts next level
}
public void EndCurrent()
{
//ends current level
currentLevel++;
if (days[currentLevel].AddsJob)
{
// add a job to pool
// if this brings us over maximum, change a job instead
}
}
}
``` |
fb4a4a9f-29cf-43fe-bd88-c074c0128749 | {
"language": "C#"
} | ```c#
using System;
using System.Text.RegularExpressions;
using Should;
using Xunit;
namespace Cassette.UI
{
public class PlaceholderTracker_Tests
{
[Fact]
public void WhenInsertPlaceholder_ThenPlaceholderIdHtmlReturned()
{
var tracker = new PlaceholderTracker();
var result = tracker.InsertPlaceholder(() => (""));
var guidRegex = new Regex(@"[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}");
var output = result;
guidRegex.IsMatch(output).ShouldBeTrue();
}
[Fact]
public void GivenInsertPlaceholder_WhenReplacePlaceholders_ThenHtmlInserted()
{
var tracker = new PlaceholderTracker();
var html = tracker.InsertPlaceholder(() => ("<p>test</p>"));
tracker.ReplacePlaceholders(html).ShouldEqual(
Environment.NewLine + "<p>test</p>" + Environment.NewLine
);
}
}
}
```
Move test into correct namespace. | ```c#
using System;
using System.Text.RegularExpressions;
using Should;
using Xunit;
namespace Cassette
{
public class PlaceholderTracker_Tests
{
[Fact]
public void WhenInsertPlaceholder_ThenPlaceholderIdHtmlReturned()
{
var tracker = new PlaceholderTracker();
var result = tracker.InsertPlaceholder(() => (""));
var guidRegex = new Regex(@"[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}");
var output = result;
guidRegex.IsMatch(output).ShouldBeTrue();
}
[Fact]
public void GivenInsertPlaceholder_WhenReplacePlaceholders_ThenHtmlInserted()
{
var tracker = new PlaceholderTracker();
var html = tracker.InsertPlaceholder(() => ("<p>test</p>"));
tracker.ReplacePlaceholders(html).ShouldEqual(
Environment.NewLine + "<p>test</p>" + Environment.NewLine
);
}
}
}``` |
1048fc31-fb49-4d07-b8e3-6da610b7a80a | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Modix.Services.StackExchange
{
public class StackExchangeService
{
private string _ApiReferenceUrl =
$"http://api.stackexchange.com/2.2/search/advanced" +
"?key={0}" +
$"&order=desc" +
$"&sort=votes" +
$"&filter=default";
public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags)
{
_ApiReferenceUrl = string.Format(_ApiReferenceUrl, token);
phrase = Uri.EscapeDataString(phrase);
site = Uri.EscapeDataString(site);
tags = Uri.EscapeDataString(tags);
var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}";
var client = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
});
var response = await client.GetAsync(query);
if (!response.IsSuccessStatusCode)
{
throw new WebException("Something failed while querying the Stack Exchange API.");
}
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<StackExchangeResponse>(json);
}
}
}
```
Use static HttpClient in SO module | ```c#
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Modix.Services.StackExchange
{
public class StackExchangeService
{
private static HttpClient HttpClient => new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
});
private string _ApiReferenceUrl =
$"http://api.stackexchange.com/2.2/search/advanced" +
"?key={0}" +
$"&order=desc" +
$"&sort=votes" +
$"&filter=default";
public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags)
{
_ApiReferenceUrl = string.Format(_ApiReferenceUrl, token);
phrase = Uri.EscapeDataString(phrase);
site = Uri.EscapeDataString(site);
tags = Uri.EscapeDataString(tags);
var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}";
var response = await HttpClient.GetAsync(query);
if (!response.IsSuccessStatusCode)
{
throw new WebException("Something failed while querying the Stack Exchange API.");
}
var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<StackExchangeResponse>(jsonResponse);
}
}
}
``` |
2eecd8c0-4ea7-4a3e-ac63-0f01f8f87af2 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle(".NET Winforms Gantt Chart Control")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Braincase Solutions")]
[assembly: AssemblyProduct("GanttChartControl")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("e316b126-c783-4060-95b9-aa8ee2e676d7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.3")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Fix assembly and file versions | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle(".NET Winforms Gantt Chart Control")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Braincase Solutions")]
[assembly: AssemblyProduct("GanttChartControl")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("e316b126-c783-4060-95b9-aa8ee2e676d7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.4")]
``` |
ec0b1fab-b2db-40b9-bae1-d13d62aed96a | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Consul.Test
{
[TestClass]
public class CoordinateTest
{
[TestMethod]
public void TestCoordinate_Datacenters()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var datacenters = client.Coordinate.Datacenters();
Assert.IsNotNull(datacenters.Response);
Assert.IsTrue(datacenters.Response.Length > 0);
}
[TestMethod]
public void TestCoordinate_Nodes()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var nodes = client.Coordinate.Nodes();
Assert.IsNotNull(nodes.Response);
Assert.IsTrue(nodes.Response.Length > 0);
}
}
}
```
Reduce testing of coordinate nodes call | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Consul.Test
{
[TestClass]
public class CoordinateTest
{
[TestMethod]
public void Coordinate_Datacenters()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var datacenters = client.Coordinate.Datacenters();
Assert.IsNotNull(datacenters.Response);
Assert.IsTrue(datacenters.Response.Length > 0);
}
[TestMethod]
public void Coordinate_Nodes()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var nodes = client.Coordinate.Nodes();
// There's not a good way to populate coordinates without
// waiting for them to calculate and update, so the best
// we can do is call the endpoint and make sure we don't
// get an error. - from offical API.
Assert.IsNotNull(nodes);
}
}
}
``` |
012da4db-4051-4f7f-aa60-2519e304be7f | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using PackageExplorerViewModel;
namespace PackageExplorer
{
public class PackageIconConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values?.Length > 1 && values[0] is PackageViewModel package && values[1] is string str && !string.IsNullOrEmpty(str))
{
var metadata = package.PackageMetadata;
if (!string.IsNullOrEmpty(metadata.Icon))
{
foreach (var file in package.RootFolder.GetFiles())
{
if (string.Equals(file.Path, metadata.Icon, StringComparison.OrdinalIgnoreCase))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = file.GetStream();
image.EndInit();
return image;
}
}
}
if (metadata.IconUrl != null)
{
var image = new BitmapImage();
image.BeginInit();
image.UriSource = metadata.IconUrl;
image.EndInit();
return image;
}
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
```
Normalize directory separator char for finding the embedded icon | ```c#
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using PackageExplorerViewModel;
namespace PackageExplorer
{
public class PackageIconConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values?.Length > 1 && values[0] is PackageViewModel package && values[1] is string str && !string.IsNullOrEmpty(str))
{
var metadata = package.PackageMetadata;
if (!string.IsNullOrEmpty(metadata.Icon))
{
// Normalize any directories to match what's the package
// We do this here instead of the metadata so that we round-trip
// whatever the user originally had when in edit view
var iconPath = metadata.Icon.Replace('/', '\\');
foreach (var file in package.RootFolder.GetFiles())
{
if (string.Equals(file.Path, iconPath, StringComparison.OrdinalIgnoreCase))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = file.GetStream();
image.EndInit();
return image;
}
}
}
if (metadata.IconUrl != null)
{
var image = new BitmapImage();
image.BeginInit();
image.UriSource = metadata.IconUrl;
image.EndInit();
return image;
}
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
``` |
4772a318-0548-478d-9bc5-28d8de47f2a2 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Diagnostics;
namespace Octokit
{
/// <summary>
/// An enhanced git commit containing links to additional resources
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class GitHubCommit : GitReference
{
public GitHubCommit() { }
public GitHubCommit(string url, string label, string @ref, string sha, User user, Repository repository, Author author, string commentsUrl, Commit commit, Author committer, string htmlUrl, GitHubCommitStats stats, IReadOnlyList<GitReference> parents, IReadOnlyList<GitHubCommitFile> files)
: base(url, label, @ref, sha, user, repository)
{
Author = author;
CommentsUrl = commentsUrl;
Commit = commit;
Committer = committer;
HtmlUrl = htmlUrl;
Stats = stats;
Parents = parents;
Files = files;
}
public Author Author { get; protected set; }
public string CommentsUrl { get; protected set; }
public Commit Commit { get; protected set; }
public Author Committer { get; protected set; }
public string HtmlUrl { get; protected set; }
public GitHubCommitStats Stats { get; protected set; }
public IReadOnlyList<GitReference> Parents { get; protected set; }
public IReadOnlyList<GitHubCommitFile> Files { get; protected set; }
}
}
```
Add doc comments for Author and Committer | ```c#
using System.Collections.Generic;
using System.Diagnostics;
namespace Octokit
{
/// <summary>
/// An enhanced git commit containing links to additional resources
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class GitHubCommit : GitReference
{
public GitHubCommit() { }
public GitHubCommit(string url, string label, string @ref, string sha, User user, Repository repository, Author author, string commentsUrl, Commit commit, Author committer, string htmlUrl, GitHubCommitStats stats, IReadOnlyList<GitReference> parents, IReadOnlyList<GitHubCommitFile> files)
: base(url, label, @ref, sha, user, repository)
{
Author = author;
CommentsUrl = commentsUrl;
Commit = commit;
Committer = committer;
HtmlUrl = htmlUrl;
Stats = stats;
Parents = parents;
Files = files;
}
/// <summary>
/// Gets the GitHub account information for the commit author. It attempts to match the email
/// address used in the commit with the email addresses registered with the GitHub account.
/// If no account corresponds to the commit email, then this property is null.
/// </summary>
public Author Author { get; protected set; }
public string CommentsUrl { get; protected set; }
public Commit Commit { get; protected set; }
/// <summary>
/// Gets the GitHub account information for the commit committer. It attempts to match the email
/// address used in the commit with the email addresses registered with the GitHub account.
/// If no account corresponds to the commit email, then this property is null.
/// </summary>
public Author Committer { get; protected set; }
public string HtmlUrl { get; protected set; }
public GitHubCommitStats Stats { get; protected set; }
public IReadOnlyList<GitReference> Parents { get; protected set; }
public IReadOnlyList<GitHubCommitFile> Files { get; protected set; }
}
}
``` |
dc6c6024-7584-4155-97df-b21d8f4b1e59 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
internal static class Extensions
{
public static Task<bool> ToTask(this WaitHandle handle, int? timeoutMilliseconds)
{
RegisteredWaitHandle registeredHandle = null;
var tcs = new TaskCompletionSource<bool>();
registeredHandle = ThreadPool.RegisterWaitForSingleObject(
handle,
(_, timedOut) =>
{
tcs.TrySetResult(!timedOut);
if (!timedOut)
{
registeredHandle.Unregister(waitObject: null);
}
},
null,
timeoutMilliseconds ?? -1,
executeOnlyOnce: true);
return tcs.Task;
}
public static async Task<bool> WaitOneAsync(this WaitHandle handle, int? timeoutMilliseconds = null) => await handle.ToTask(timeoutMilliseconds);
public static async ValueTask<T> TakeAsync<T>(this BlockingCollection<T> collection, TimeSpan? pollTimeSpan = null, CancellationToken cancellationToken = default)
{
var delay = pollTimeSpan ?? TimeSpan.FromSeconds(.25);
do
{
if (collection.TryTake(out T value))
{
return value;
}
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
} while (true);
}
}
}
```
Fix race in VBCSCompiler test | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
internal static class Extensions
{
public static Task ToTask(this WaitHandle handle, int? timeoutMilliseconds)
{
RegisteredWaitHandle registeredHandle = null;
var tcs = new TaskCompletionSource<object>();
registeredHandle = ThreadPool.RegisterWaitForSingleObject(
handle,
(_, timeout) =>
{
tcs.TrySetResult(null);
if (registeredHandle is object)
{
registeredHandle.Unregister(waitObject: null);
}
},
null,
timeoutMilliseconds ?? -1,
executeOnlyOnce: true);
return tcs.Task;
}
public static async Task WaitOneAsync(this WaitHandle handle, int? timeoutMilliseconds = null) => await handle.ToTask(timeoutMilliseconds);
public static async ValueTask<T> TakeAsync<T>(this BlockingCollection<T> collection, TimeSpan? pollTimeSpan = null, CancellationToken cancellationToken = default)
{
var delay = pollTimeSpan ?? TimeSpan.FromSeconds(.25);
do
{
if (collection.TryTake(out T value))
{
return value;
}
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
} while (true);
}
}
}
``` |
b0b6939c-2d15-4820-9688-85e0bf9663b5 | {
"language": "C#"
} | ```c#
using System;
using System.Drawing;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontAndStyle_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
}
}
}
```
Fix mono bug in the FontHelper class | ```c#
using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
}
}
}
``` |
cad22486-3bdd-4880-b756-3d0ba0da3ff8 | {
"language": "C#"
} | ```c#
/*
* Copyright 2017 Chirojeugd-Vlaanderen vzw. See the NOTICE file at the
* top-level directory of this distribution, and at
* https://gapwiki.chiro.be/copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using Chiro.Gap.Api.Models;
using Chiro.Gap.ServiceContracts.DataContracts;
namespace Chiro.Gap.Api
{
public static class MappingHelper
{
public static void CreateMappings()
{
// TODO: Damn, nog steeds automapper 3. (zie #5401).
Mapper.CreateMap<GroepInfo, GroepModel>();
}
}
}```
Remove trailing spaces from stamnummer. | ```c#
/*
* Copyright 2017 Chirojeugd-Vlaanderen vzw. See the NOTICE file at the
* top-level directory of this distribution, and at
* https://gapwiki.chiro.be/copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AutoMapper;
using Chiro.Gap.Api.Models;
using Chiro.Gap.ServiceContracts.DataContracts;
namespace Chiro.Gap.Api
{
public static class MappingHelper
{
public static void CreateMappings()
{
// TODO: Damn, nog steeds automapper 3. (zie #5401).
Mapper.CreateMap<GroepInfo, GroepModel>()
.ForMember(dst => dst.StamNummer, opt => opt.MapFrom(src => src.StamNummer.Trim()));
}
}
}``` |
a6fc0f78-f9ec-459b-897f-94bacb8f9141 | {
"language": "C#"
} | ```c#
/* Empiria Extensions Framework ******************************************************************************
* *
* Solution : Empiria Extensions Framework System : Empiria Microservices *
* Namespace : Empiria.Microservices Assembly : Empiria.Microservices.dll *
* Type : LoggingController Pattern : Web API Controller *
* Version : 1.0 License : Please read license.txt file *
* *
* Summary : Contains web api methods for application log services. *
* *
********************************** Copyright(c) 2016-2017. La Vía Óntica SC, Ontica LLC and contributors. **/
using System;
using System.Web.Http;
using Empiria.Logging;
using Empiria.Security;
using Empiria.WebApi;
namespace Empiria.Microservices {
/// <summary>Contains web api methods for application log services.</summary>
public class LoggingController : WebApiController {
#region Public APIs
/// <summary>Stores an array of log entries.</summary>
/// <param name="logEntries">The non-empty array of LogEntryModel instances.</param>
[HttpPost, AllowAnonymous]
[Route("v1/logging")]
public void PostLogEntryArray(string apiKey, [FromBody] LogEntryModel[] logEntries) {
try {
ClientApplication clientApplication = base.GetClientApplication();
var logTrail = new LogTrail(clientApplication);
logTrail.Write(logEntries);
} catch (Exception e) {
throw base.CreateHttpException(e);
}
}
#endregion Public APIs
} // class LoggingController
} // namespace Empiria.Microservices
```
Fix remove logging controller apiKey parameter | ```c#
/* Empiria Extensions Framework ******************************************************************************
* *
* Module : Empiria Web Api Component : Base controllers *
* Assembly : Empiria.WebApi.dll Pattern : Web Api Controller *
* Type : LoggingController License : Please read LICENSE.txt file *
* *
* Summary : Contains web api methods for application log services. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using System.Web.Http;
using Empiria.Logging;
using Empiria.Security;
namespace Empiria.WebApi.Controllers {
/// <summary>Contains web api methods for application log services.</summary>
public class LoggingController : WebApiController {
#region Public APIs
/// <summary>Stores an array of log entries.</summary>
/// <param name="logEntries">The non-empty array of LogEntryModel instances.</param>
[HttpPost, AllowAnonymous]
[Route("v1/logging")]
public void PostLogEntryArray([FromBody] LogEntryModel[] logEntries) {
try {
ClientApplication clientApplication = base.GetClientApplication();
var logTrail = new LogTrail(clientApplication);
logTrail.Write(logEntries);
} catch (Exception e) {
throw base.CreateHttpException(e);
}
}
#endregion Public APIs
} // class LoggingController
} // namespace Empiria.WebApi.Controllers
``` |
ddade4ce-e460-4791-afa1-b1024090ad3c | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using Windows.Storage;
namespace Papyrus
{
public static class EBookExtensions
{
public static async Task<bool> VerifyMimetypeAsync(this EBook ebook)
{
var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype");
if (mimetypeFile == null) // Make sure file exists.
return false;
var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile);
if (fileContents != "application/epub+zip") // Make sure file contents are correct.
return false;
return true;
}
}
}
```
Use local function to verify mimetype string. | ```c#
using System;
using System.Threading.Tasks;
using Windows.Storage;
namespace Papyrus
{
public static class EBookExtensions
{
public static async Task<bool> VerifyMimetypeAsync(this EBook ebook)
{
bool VerifyMimetypeString(string value) =>
value == "application/epub+zip";
if (ebook._rootFolder == null) // Make sure a root folder was specified.
return false;
var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype");
if (mimetypeFile == null) // Make sure file exists.
return false;
var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile);
if (!VerifyMimetypeString(fileContents)) // Make sure file contents are correct.
return false;
return true;
}
}
}
``` |
9da8e092-437b-4c68-bbb2-ad0343661083 | {
"language": "C#"
} | ```c#
using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;
namespace WalletWasabi.Gui.Shell.MainMenu
{
internal class ToolsMainMenuItems
{
private IMenuItemFactory _menuItemFactory;
[ImportingConstructor]
public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
{
_menuItemFactory = menuItemFactory;
}
#region MainMenu
[ExportMainMenuItem("Tools")]
[DefaultOrder(1)]
public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);
#endregion MainMenu
#region Group
[ExportMainMenuDefaultGroup("Tools", "Managers")]
[DefaultOrder(0)]
public object ManagersGroup => null;
[ExportMainMenuDefaultGroup("Tools", "Settings")]
[DefaultOrder(1)]
public object SettingsGroup => null;
#endregion Group
#region MenuItem
[ExportMainMenuItem("Tools", "Wallet Manager")]
[DefaultOrder(0)]
[DefaultGroup("Managers")]
public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");
[ExportMainMenuItem("Tools", "Settings")]
[DefaultOrder(1)]
[DefaultGroup("Settings")]
public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");
#endregion MenuItem
}
}
```
Rename GenerateWallet menuitem to WalletManager | ```c#
using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;
namespace WalletWasabi.Gui.Shell.MainMenu
{
internal class ToolsMainMenuItems
{
private IMenuItemFactory _menuItemFactory;
[ImportingConstructor]
public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
{
_menuItemFactory = menuItemFactory;
}
#region MainMenu
[ExportMainMenuItem("Tools")]
[DefaultOrder(1)]
public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);
#endregion MainMenu
#region Group
[ExportMainMenuDefaultGroup("Tools", "Managers")]
[DefaultOrder(0)]
public object ManagersGroup => null;
[ExportMainMenuDefaultGroup("Tools", "Settings")]
[DefaultOrder(1)]
public object SettingsGroup => null;
#endregion Group
#region MenuItem
[ExportMainMenuItem("Tools", "Wallet Manager")]
[DefaultOrder(0)]
[DefaultGroup("Managers")]
public IMenuItem WalletManager => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");
[ExportMainMenuItem("Tools", "Settings")]
[DefaultOrder(1)]
[DefaultGroup("Settings")]
public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");
#endregion MenuItem
}
}
``` |
392340cc-dc59-4eeb-afc1-3bfd744b74ab | {
"language": "C#"
} | ```c#
using NBitcoin;
using Newtonsoft.Json;
using System;
namespace WalletWasabi.JsonConverters
{
public class ExtPubKeyJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ExtPubKey);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var hex = (string)reader.Value;
return new ExtPubKey(ByteHelpers.FromHex(hex));
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var epk = (ExtPubKey)value;
var hex = ByteHelpers.ToHex(epk.ToBytes());
writer.WriteValue(hex);
}
}
}
```
Save xpub instead of hex (wallet compatibility) | ```c#
using NBitcoin;
using Newtonsoft.Json;
using System;
namespace WalletWasabi.JsonConverters
{
public class ExtPubKeyJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ExtPubKey);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var s = (string)reader.Value;
ExtPubKey epk;
try
{
epk = ExtPubKey.Parse(s);
}
catch
{
// Try hex, Old wallet format was like this.
epk = new ExtPubKey(ByteHelpers.FromHex(s));
}
return epk;
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var epk = (ExtPubKey)value;
var xpub = epk.GetWif(Network.Main).ToWif();
writer.WriteValue(xpub);
}
}
}
``` |
847b85ae-5e56-44bc-80b8-62731c03959a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using Draw = System.Drawing;
using Geo = ERY.AgateLib.Geometry;
namespace ERY.AgateLib.WinForms
{
public static class FormsInterop
{
public static Draw.Rectangle ToRectangle(Geo.Rectangle rect)
{
return new System.Drawing.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
}
}
}
```
Add converters for System.Drawing structures. | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using Draw = System.Drawing;
using ERY.AgateLib.Geometry;
namespace ERY.AgateLib.WinForms
{
public static class FormsInterop
{
public static Draw.Color ConvertColor(Color clr)
{
return Draw.Color.FromArgb(clr.ToArgb());
}
public static Color ConvertColor(Draw.Color clr)
{
return Color.FromArgb(clr.ToArgb());
}
public static Draw.Rectangle ConvertRectangle(Rectangle rect)
{
return new Draw.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
}
public static Rectangle ConvertRectangle(Draw.Rectangle rect)
{
return new Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
}
public static Draw.RectangleF ConvertRectangleF(RectangleF rect)
{
return new Draw.RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
}
public static RectangleF ConvertRectangleF(Draw.RectangleF rect)
{
return new RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
}
public static Point ConvertPoint(Draw.Point pt)
{
return new Point(pt.X, pt.Y);
}
public static Draw.Point ConvertPoint(Point pt)
{
return new Draw.Point(pt.X, pt.Y);
}
public static PointF ConvertPointF(Draw.PointF pt)
{
return new PointF(pt.X, pt.Y);
}
public static Draw.PointF ConvertPointF(PointF pt)
{
return new Draw.PointF(pt.X, pt.Y);
}
public static Size ConvertSize(Draw.Size pt)
{
return new Size(pt.Width, pt.Height);
}
public static Draw.Size ConvertSize(Size pt)
{
return new Draw.Size(pt.Width, pt.Height);
}
public static SizeF ConvertSizeF(Draw.SizeF pt)
{
return new SizeF(pt.Width, pt.Height);
}
public static Draw.SizeF ConvertSizeF(SizeF pt)
{
return new Draw.SizeF(pt.Width, pt.Height);
}
}
}
``` |
b4fdbc0e-bae0-4a7c-a3d7-659f6ec70302 | {
"language": "C#"
} | ```c#
using System.Text.RegularExpressions;
namespace MarekMotykaBot.ExtensionsMethods
{
public static class StringExtensions
{
public static string RemoveRepeatingChars(this string inputString)
{
string newString = string.Empty;
char[] charArray = inputString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if (string.IsNullOrEmpty(newString))
newString += charArray[i].ToString();
else if (newString[newString.Length - 1] != charArray[i])
newString += charArray[i].ToString();
}
return newString;
}
public static string RemoveEmojis(this string inputString)
{
return Regex.Replace(inputString, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}
public static string RemoveEmotes(this string inputString)
{
return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
}
public static string RemoveEmojisAndEmotes(this string inputString)
{
return inputString.RemoveEmotes().RemoveEmojis();
}
}
}```
Allow spaces in !meme command. | ```c#
using System.Text.RegularExpressions;
namespace MarekMotykaBot.ExtensionsMethods
{
public static class StringExtensions
{
public static string RemoveRepeatingChars(this string inputString)
{
string newString = string.Empty;
char[] charArray = inputString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if (string.IsNullOrEmpty(newString))
newString += charArray[i].ToString();
else if (newString[newString.Length - 1] != charArray[i])
newString += charArray[i].ToString();
}
return newString;
}
public static string RemoveEmojis(this string inputString)
{
return Regex.Replace(inputString, @"[^a-zA-Z0-9\s]+", "", RegexOptions.Compiled);
}
public static string RemoveEmotes(this string inputString)
{
return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
}
public static string RemoveEmojisAndEmotes(this string inputString)
{
return inputString.RemoveEmotes().RemoveEmojis();
}
}
}``` |
5d9bf72a-5437-48d5-85d8-c144a03868e5 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("libcmdline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libcmdline")]
[assembly: AssemblyCopyright("")]
[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("853c7fe9-e12b-484c-93de-3f3de6907860")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Change version to a reasonable value | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("libcmdline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libcmdline")]
[assembly: AssemblyCopyright("")]
[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("853c7fe9-e12b-484c-93de-3f3de6907860")]
// 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("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
``` |
90fc913d-0784-4e49-8904-591df87695d0 | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VirusTotalNET.Exceptions;
namespace VirusTotalNET.DateTimeParsers
{
public class YearMonthDayConverter : DateTimeConverterBase
{
private readonly CultureInfo _culture = new CultureInfo("en-us");
private const string _dateFormatString = "yyyyMMdd";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.DateFormatString = _dateFormatString;
writer.WriteValue(value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return DateTime.MinValue;
if (!(reader.Value is string))
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + reader.Value);
string value = (string)reader.Value;
if (DateTime.TryParseExact(value, _dateFormatString, _culture, DateTimeStyles.AllowWhiteSpaces, out DateTime result))
return result;
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + value);
}
}
}```
Fix a bug where dates are sometimes '-' | ```c#
using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VirusTotalNET.Exceptions;
namespace VirusTotalNET.DateTimeParsers
{
public class YearMonthDayConverter : DateTimeConverterBase
{
private readonly CultureInfo _culture = new CultureInfo("en-us");
private const string _dateFormatString = "yyyyMMdd";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.DateFormatString = _dateFormatString;
writer.WriteValue(value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return DateTime.MinValue;
if (!(reader.Value is string))
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + reader.Value);
string value = (string)reader.Value;
//VT sometimes have really old data that return '-' in timestamps
if (value.Equals("-", StringComparison.OrdinalIgnoreCase))
return DateTime.MinValue;
if (DateTime.TryParseExact(value, _dateFormatString, _culture, DateTimeStyles.AllowWhiteSpaces, out DateTime result))
return result;
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + value);
}
}
}``` |
f963af86-b9f2-4a6f-959a-783702d69d03 | {
"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.ComponentModel;
namespace osu.Game.Configuration
{
public enum ScoreMeterType
{
[Description("None")]
None,
[Description("Hit Error (left)")]
HitErrorLeft,
[Description("Hit Error (right)")]
HitErrorRight,
[Description("Hit Error (both)")]
HitErrorBoth,
}
}
```
Add more types to dropdown | ```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.ComponentModel;
namespace osu.Game.Configuration
{
public enum ScoreMeterType
{
[Description("None")]
None,
[Description("Hit Error (left)")]
HitErrorLeft,
[Description("Hit Error (right)")]
HitErrorRight,
[Description("Hit Error (both)")]
HitErrorBoth,
[Description("Colour (left)")]
ColourLeft,
[Description("Colour (right)")]
ColourRight,
[Description("Colour (both)")]
ColourBoth,
}
}
``` |
ba90fe28-51f8-47a4-8e16-eaa7ef42122d | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
namespace AudioWorks.Common
{
/// <summary>
/// Manages the retrieval of configuration settings from disk.
/// </summary>
public static class ConfigurationManager
{
/// <summary>
/// Gets the configuration.
/// </summary>
/// <value>The configuration.</value>
[NotNull]
[CLSCompliant(false)]
public static IConfigurationRoot Configuration { get; }
static ConfigurationManager()
{
var settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"AudioWorks");
const string settingsFileName = "settings.json";
// Copy the settings template if the file doesn't already exist
var settingsFile = Path.Combine(settingsPath, settingsFileName);
if (!File.Exists(settingsFile))
{
Directory.CreateDirectory(settingsPath);
File.Copy(
// ReSharper disable once AssignNullToNotNullAttribute
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), settingsFileName),
settingsFile);
}
Configuration = new ConfigurationBuilder()
.SetBasePath(settingsPath)
.AddJsonFile(settingsFileName, true)
.Build();
}
}
}
```
Correct issue where settings.json cannot be found when using a shadow copied DLL. | ```c#
using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
namespace AudioWorks.Common
{
/// <summary>
/// Manages the retrieval of configuration settings from disk.
/// </summary>
public static class ConfigurationManager
{
/// <summary>
/// Gets the configuration.
/// </summary>
/// <value>The configuration.</value>
[NotNull]
[CLSCompliant(false)]
public static IConfigurationRoot Configuration { get; }
static ConfigurationManager()
{
var settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"AudioWorks");
const string settingsFileName = "settings.json";
// Copy the settings template if the file doesn't already exist
var settingsFile = Path.Combine(settingsPath, settingsFileName);
if (!File.Exists(settingsFile))
{
Directory.CreateDirectory(settingsPath);
File.Copy(
Path.Combine(
// ReSharper disable once AssignNullToNotNullAttribute
Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath),
settingsFileName),
settingsFile);
}
Configuration = new ConfigurationBuilder()
.SetBasePath(settingsPath)
.AddJsonFile(settingsFileName, true)
.Build();
}
}
}
``` |
53830c77-36ac-4c0d-bec6-f93d3b599cf9 | {
"language": "C#"
} | ```c#
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
namespace RohlikAPITests
{
[TestClass]
public class RohlikovacTests
{
private string[] GetCredentials()
{
string filePath = @"..\..\..\loginPassword.txt";
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Test needs credentials. Create 'loginPassword.txt' in solution root directory. Enter username@email.com:yourPassword on first line.");
}
var passwordString = File.ReadAllText(filePath);
return passwordString.Split(':');
}
[TestMethod]
public void RunTest()
{
var login = GetCredentials();
var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
var result = rohlikApi.RunRohlikovac();
if (result.Contains("error"))
{
Assert.Fail($"Failed to login to rohlik. Login used: {login[0]}");
}
}
}
}```
Add test category to authenticated test | ```c#
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
namespace RohlikAPITests
{
[TestClass]
public class RohlikovacTests
{
private string[] GetCredentials()
{
string filePath = @"..\..\..\loginPassword.txt";
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Test needs credentials. Create 'loginPassword.txt' in solution root directory. Enter username@email.com:yourPassword on first line.");
}
var passwordString = File.ReadAllText(filePath);
return passwordString.Split(':');
}
[TestMethod, TestCategory("Authenticated")]
public void RunTest()
{
var login = GetCredentials();
var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
var result = rohlikApi.RunRohlikovac();
if (result.Contains("error"))
{
Assert.Fail($"Failed to login to rohlik. Login used: {login[0]}");
}
}
}
}``` |
08300984-b461-4e1f-bc54-a9be356047e8 | {
"language": "C#"
} | ```c#
using System;
using Reachmail.Easysmtp.Post.Request;
public void Main()
{
var reachmail = Reachmail.Api.Create("<API Token>");
var request = new DeliveryRequest {
FromAddress = "from@from.com",
Recipients = new Recipients {
new Recipient {
Address = "to@to.com"
}
},
Subject = "Subject",
BodyText = "Text",
BodyHtml = "<p>html</p>",
Headers = new Headers {
{ "name", "value" }
},
Attachments = new Attachments {
new EmailAttachment {
Filename = "text.txt",
Data = "b2ggaGFp", // Base64 encoded
ContentType = "text/plain",
ContentDisposition = "attachment",
Cid = "<text.txt>"
}
},
Tracking = true,
FooterAddress = "footer@footer.com",
SignatureDomain = "signature.net"
};
var result = reachmail.Easysmtp.Post(request);
}```
Tweak to content for display on ES marketing site | ```c#
using System;
using Reachmail.Easysmtp.Post.Request;
public void Main()
{
var reachmail = Reachmail.Api.Create("<API Token>");
var request = new DeliveryRequest {
FromAddress = "from@from.com",
Recipients = new Recipients {
new Recipient {
Address = "to@to.com"
}
},
Subject = "Subject",
BodyText = "Text",
BodyHtml = "html",
Headers = new Headers {
{ "name", "value" }
},
Attachments = new Attachments {
new EmailAttachment {
Filename = "text.txt",
Data = "b2ggaGFp", // Base64 encoded
ContentType = "text/plain",
ContentDisposition = "attachment",
Cid = "<text.txt>"
}
},
Tracking = true,
FooterAddress = "footer@footer.com",
SignatureDomain = "signature.net"
};
var result = reachmail.Easysmtp.Post(request);
}
``` |
dd13d7fd-34eb-4df9-919b-a4537dae238e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using System.Threading.Tasks;
namespace ContactsBot.Modules
{
class UserMotd : IMessageAction
{
private DiscordSocketClient _client;
private BotConfiguration _config;
public bool IsEnabled { get; private set; }
public void Install(IDependencyMap map)
{
_client = map.Get<DiscordSocketClient>();
_config = map.Get<BotConfiguration>();
}
public void Enable()
{
_client.UserJoined += ShowMotd;
IsEnabled = true;
}
public void Disable()
{
_client.UserJoined -= ShowMotd;
IsEnabled = false;
}
public async Task ShowMotd(SocketGuildUser user)
{
var channel = await user.Guild.GetDefaultChannelAsync();
try
{
await channel.SendMessageAsync(String.Format(_config.MessageOfTheDay, user.Mention));
}
catch (FormatException)
{
await channel.SendMessageAsync("Tell the admin to fix the MOTD formatting!");
}
}
}
}
```
Send message as DM, not default channel | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using System.Threading.Tasks;
namespace ContactsBot.Modules
{
class UserMotd : IMessageAction
{
private DiscordSocketClient _client;
private BotConfiguration _config;
public bool IsEnabled { get; private set; }
public void Install(IDependencyMap map)
{
_client = map.Get<DiscordSocketClient>();
_config = map.Get<BotConfiguration>();
}
public void Enable()
{
_client.UserJoined += ShowMotd;
IsEnabled = true;
}
public void Disable()
{
_client.UserJoined -= ShowMotd;
IsEnabled = false;
}
public async Task ShowMotd(SocketGuildUser user)
{
var channel = await user.Guild.GetDefaultChannelAsync();
try
{
await (await user.CreateDMChannelAsync()).SendMessageAsync(String.Format(_config.MessageOfTheDay, user.Mention));
}
catch (FormatException)
{
await channel.SendMessageAsync("Tell the admin to fix the MOTD formatting!");
}
}
}
}
``` |
4040ac91-8d21-408a-999f-5ea31d44a932 | {
"language": "C#"
} | ```c#
using System;
using Cake.Frosting;
public class Program
{
public static int Main(string[] args)
{
return new CakeHost()
.UseContext<Context>()
.UseLifetime<Lifetime>()
.UseWorkingDirectory("..")
.InstallTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"))
.InstallTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"))
.InstallTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"))
.InstallTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"))
.Run(args);
}
}
```
Fix tools being installed to wrong path | ```c#
using System;
using Cake.Frosting;
public class Program
{
public static int Main(string[] args)
{
return new CakeHost()
.UseContext<Context>()
.UseLifetime<Lifetime>()
.UseWorkingDirectory("..")
.SetToolPath("../tools")
.InstallTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"))
.InstallTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"))
.InstallTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"))
.InstallTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"))
.Run(args);
}
}
``` |
6716fb15-108d-489b-afe5-97730e15c3e3 | {
"language": "C#"
} | ```c#
using System.Reactive.Linq;
using ReactiveUI;
using System;
namespace WalletWasabi.Fluent.ViewModels
{
public class AddWalletPageViewModel : NavBarItemViewModel
{
private string _walletName = "";
private bool _optionsEnabled;
public AddWalletPageViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.Dialog)
{
Title = "Add Wallet";
this.WhenAnyValue(x => x.WalletName)
.Select(x => !string.IsNullOrWhiteSpace(x))
.Subscribe(x => OptionsEnabled = x);
}
public override string IconName => "add_circle_regular";
public string WalletName
{
get => _walletName;
set => this.RaiseAndSetIfChanged(ref _walletName, value);
}
public bool OptionsEnabled
{
get => _optionsEnabled;
set => this.RaiseAndSetIfChanged(ref _optionsEnabled, value);
}
}
}
```
Add back and cancel button commands | ```c#
using System.Reactive.Linq;
using ReactiveUI;
using System;
using System.Windows.Input;
namespace WalletWasabi.Fluent.ViewModels
{
public class AddWalletPageViewModel : NavBarItemViewModel
{
private string _walletName = "";
private bool _optionsEnabled;
public AddWalletPageViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.Dialog)
{
Title = "Add Wallet";
BackCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear());
CancelCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear());
this.WhenAnyValue(x => x.WalletName)
.Select(x => !string.IsNullOrWhiteSpace(x))
.Subscribe(x => OptionsEnabled = x);
}
public override string IconName => "add_circle_regular";
public ICommand BackCommand { get; }
public ICommand CancelCommand { get; }
public string WalletName
{
get => _walletName;
set => this.RaiseAndSetIfChanged(ref _walletName, value);
}
public bool OptionsEnabled
{
get => _optionsEnabled;
set => this.RaiseAndSetIfChanged(ref _optionsEnabled, value);
}
}
}
``` |
e5c2cd8d-6b2b-4202-a175-34250469dcde | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Kazyx.RemoteApi
{
/// <summary>
/// Response of getMethodTypes API.
/// </summary>
public class MethodType
{
/// <summary>
/// Name of API
/// </summary>
public string Name { set; get; }
/// <summary>
/// Request parameter types.
/// </summary>
public List<string> ReqTypes { set; get; }
/// <summary>
/// Response parameter types.
/// </summary>
public List<string> ResTypes { set; get; }
/// <summary>
/// Version of API
/// </summary>
public string Version { set; get; }
}
/// <summary>
/// Set of current value and its candidates.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Capability<T>
{
/// <summary>
/// Current value of the specified parameter.
/// </summary>
public virtual T Current { set; get; }
/// <summary>
/// Candidate values of the specified parameter.
/// </summary>
public virtual List<T> Candidates { set; get; }
public override bool Equals(object o)
{
var other = o as Capability<T>;
if (!Current.Equals(other.Current))
{
return false;
}
if (Candidates?.Count != other.Candidates?.Count)
{
return false;
}
for (int i = 0; i < Candidates.Count; i++)
{
if (!Candidates[i].Equals(other.Candidates[i]))
{
return false;
}
}
return true;
}
}
}
```
Use SequenceEqual and check null | ```c#
using System.Collections.Generic;
using System.Linq;
namespace Kazyx.RemoteApi
{
/// <summary>
/// Response of getMethodTypes API.
/// </summary>
public class MethodType
{
/// <summary>
/// Name of API
/// </summary>
public string Name { set; get; }
/// <summary>
/// Request parameter types.
/// </summary>
public List<string> ReqTypes { set; get; }
/// <summary>
/// Response parameter types.
/// </summary>
public List<string> ResTypes { set; get; }
/// <summary>
/// Version of API
/// </summary>
public string Version { set; get; }
}
/// <summary>
/// Set of current value and its candidates.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Capability<T>
{
/// <summary>
/// Current value of the specified parameter.
/// </summary>
public virtual T Current { set; get; }
/// <summary>
/// Candidate values of the specified parameter.
/// </summary>
public virtual List<T> Candidates { set; get; }
public override bool Equals(object o)
{
var other = o as Capability<T>;
if (other == null) { return false; }
if (!Current.Equals(other.Current)) { return false; }
if (Candidates?.Count != other.Candidates?.Count) { return false; }
return Candidates.SequenceEqual(other.Candidates);
}
}
}
``` |
61c15747-c5d8-4644-a7ad-2b1feed57acb | {
"language": "C#"
} | ```c#
// Copyright © 2010-2016 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;
using System.Windows;
namespace CefSharp.Wpf.Example.Handlers
{
internal class GeolocationHandler : IGeolocationHandler
{
bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback)
{
using (callback)
{
var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo);
callback.Continue(result == MessageBoxResult.Yes);
return result == MessageBoxResult.Yes;
}
}
void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId)
{
}
}
}
```
Update the GelocationHandler example - seems people are still struggling with the callback concept. | ```c#
// Copyright © 2010-2016 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;
using System.Windows;
namespace CefSharp.Wpf.Example.Handlers
{
internal class GeolocationHandler : IGeolocationHandler
{
bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback)
{
//You can execute the callback inline
//callback.Continue(true);
//return true;
//You can execute the callback in an `async` fashion
//Open a message box on the `UI` thread and ask for user input.
//You can open a form, or do whatever you like, just make sure you either
//execute the callback or call `Dispose` as it's an `unmanaged` wrapper.
var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
chromiumWebBrowser.Dispatcher.BeginInvoke((Action)(() =>
{
//Callback wraps an unmanaged resource, so we'll make sure it's Disposed (calling Continue will also Dipose of the callback, it's safe to dispose multiple times).
using (callback)
{
var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo);
//Execute the callback, to allow/deny the request.
callback.Continue(result == MessageBoxResult.Yes);
}
}));
//Yes we'd like to hadle this request ourselves.
return true;
}
void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId)
{
}
}
}
``` |
8c0c5182-48ec-46fa-ac9d-f83ad9cd4595 | {
"language": "C#"
} | ```c#
using System.Drawing;
using MonoHaven.UI.Widgets;
namespace MonoHaven.UI.Remote
{
public class ServerInventoryWidget : ServerWidget
{
public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
{
var size = (Point)args[0];
var widget = new InventoryWidget(parent.Widget);
widget.SetInventorySize(size);
return new ServerInventoryWidget(id, parent, widget);
}
public ServerInventoryWidget(ushort id, ServerWidget parent, InventoryWidget widget)
: base(id, parent, widget)
{
widget.Drop += (p) => SendMessage("drop", p);
widget.Transfer += OnTransfer;
}
private void OnTransfer(TransferEventArgs e)
{
var mods = ServerInput.ToServerModifiers(e.Modifiers);
SendMessage("xfer", e.Delta, mods);
}
}
}
```
Handle message changing inventory size | ```c#
using System.Drawing;
using MonoHaven.UI.Widgets;
namespace MonoHaven.UI.Remote
{
public class ServerInventoryWidget : ServerWidget
{
public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
{
var size = (Point)args[0];
var widget = new InventoryWidget(parent.Widget);
widget.SetInventorySize(size);
return new ServerInventoryWidget(id, parent, widget);
}
private readonly InventoryWidget widget;
public ServerInventoryWidget(ushort id, ServerWidget parent, InventoryWidget widget)
: base(id, parent, widget)
{
this.widget = widget;
this.widget.Drop += (p) => SendMessage("drop", p);
this.widget.Transfer += OnTransfer;
}
public override void ReceiveMessage(string message, object[] args)
{
if (message == "sz")
widget.SetInventorySize((Point)args[0]);
else
base.ReceiveMessage(message, args);
}
private void OnTransfer(TransferEventArgs e)
{
var mods = ServerInput.ToServerModifiers(e.Modifiers);
SendMessage("xfer", e.Delta, mods);
}
}
}
``` |
41ad4ee3-0a5e-411c-b0b3-70c1cd9b225e | {
"language": "C#"
} | ```c#
using CommandLine;
using System;
using System.IO;
using System.Threading;
using WebScriptHook.Framework;
using WebScriptHook.Framework.BuiltinPlugins;
using WebScriptHook.Framework.Plugins;
using WebScriptHook.Service.Plugins;
namespace WebScriptHook.Service
{
class Program
{
static WebScriptHookComponent wshComponent;
static void Main(string[] args)
{
string componentName = Guid.NewGuid().ToString();
Uri remoteUri;
var options = new CommandLineOptions();
if (Parser.Default.ParseArguments(args, options))
{
if (!string.IsNullOrWhiteSpace(options.Name)) componentName = options.Name;
remoteUri = new Uri(options.ServerUriString);
}
else
{
return;
}
wshComponent = new WebScriptHookComponent(componentName, remoteUri, Console.Out, LogType.All);
// Register custom plugins
wshComponent.PluginManager.RegisterPlugin(new Echo());
wshComponent.PluginManager.RegisterPlugin(new PluginList());
wshComponent.PluginManager.RegisterPlugin(new PrintToScreen());
// Load plugins in plugins directory if dir exists
if (Directory.Exists("plugins"))
{
var plugins = PluginLoader.LoadAllPluginsFromDir("plugins", "*.dll");
foreach (var plug in plugins)
{
wshComponent.PluginManager.RegisterPlugin(plug);
}
}
// Start WSH component
wshComponent.Start();
// TODO: Use a timer instead of Sleep
while (true)
{
wshComponent.Update();
Thread.Sleep(100);
}
}
}
}
```
Use polling rate of 30 | ```c#
using CommandLine;
using System;
using System.IO;
using System.Threading;
using WebScriptHook.Framework;
using WebScriptHook.Framework.BuiltinPlugins;
using WebScriptHook.Framework.Plugins;
using WebScriptHook.Service.Plugins;
namespace WebScriptHook.Service
{
class Program
{
static WebScriptHookComponent wshComponent;
static void Main(string[] args)
{
string componentName = Guid.NewGuid().ToString();
Uri remoteUri;
var options = new CommandLineOptions();
if (Parser.Default.ParseArguments(args, options))
{
if (!string.IsNullOrWhiteSpace(options.Name)) componentName = options.Name;
remoteUri = new Uri(options.ServerUriString);
}
else
{
return;
}
wshComponent = new WebScriptHookComponent(componentName, remoteUri, TimeSpan.FromMilliseconds(30), Console.Out, LogType.All);
// Register custom plugins
wshComponent.PluginManager.RegisterPlugin(new Echo());
wshComponent.PluginManager.RegisterPlugin(new PluginList());
wshComponent.PluginManager.RegisterPlugin(new PrintToScreen());
// Load plugins in plugins directory if dir exists
if (Directory.Exists("plugins"))
{
var plugins = PluginLoader.LoadAllPluginsFromDir("plugins", "*.dll");
foreach (var plug in plugins)
{
wshComponent.PluginManager.RegisterPlugin(plug);
}
}
// Start WSH component
wshComponent.Start();
// TODO: Use a timer instead of Sleep
while (true)
{
wshComponent.Update();
Thread.Sleep(100);
}
}
}
}
``` |
2ac61dbe-4590-4e85-babc-e4caed41eda1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace WootzJs.Injection
{
public class Context
{
private ICache cache;
private IDictionary<Type, IBinding> transientBindings;
public Context(Context context = null, ICache cache = null, IDictionary<Type, IBinding> transientBindings = null)
{
cache = cache ?? new Cache();
this.cache = context != null ? new HybridCache(cache, context.Cache) : cache;
this.transientBindings = transientBindings;
}
public ICache Cache
{
get { return cache; }
}
public IBinding GetCustomBinding(Type type)
{
if (transientBindings == null)
return null;
IBinding result;
transientBindings.TryGetValue(type, out result);
return result;
}
}
}```
Fix handling of transient bindings to accomodate bindings that have been specified for an ancestral type | ```c#
using System;
using System.Collections.Generic;
namespace WootzJs.Injection
{
public class Context
{
private ICache cache;
private IDictionary<Type, IBinding> transientBindings;
public Context(Context context = null, ICache cache = null, IDictionary<Type, IBinding> transientBindings = null)
{
cache = cache ?? new Cache();
this.cache = context != null ? new HybridCache(cache, context.Cache) : cache;
this.transientBindings = transientBindings;
}
public ICache Cache
{
get { return cache; }
}
public IBinding GetCustomBinding(Type type)
{
if (transientBindings == null)
return null;
while (type != null)
{
IBinding result;
if (transientBindings.TryGetValue(type, out result))
return result;
type = type.BaseType;
}
return null;
}
}
}``` |
7fa62292-130e-4839-9a61-09e0dbd5d46e | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.15")]```
Use 1.0.0 as the default informational version so it's easy to spot when it might have been un-patched during a build | ```c#
using System.Reflection;
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]``` |
6943fdae-ef62-45d5-97d5-aee618b55f41 | {
"language": "C#"
} | ```c#
#if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using UnitDriven;
namespace Csla.Test.Silverlight.Rollback
{
#if SILVERLIGHT
[TestClass]
#endif
public class RollbackTests : TestBase
{
#if SILVERLIGHT
[TestMethod]
public void UnintializedProperty_RollsBack_AfterCancelEdit()
{
var context = GetContext();
RollbackRoot.BeginCreateLocal((o, e) =>
{
var item = e.Object;
var initialValue = 0;// item.UnInitedP;
item.BeginEdit();
item.UnInitedP = 1000;
item.Another = "test";
item.CancelEdit();
context.Assert.AreEqual(initialValue, item.UnInitedP);
context.Assert.Success();
});
context.Complete();
}
#endif
}
}
```
Add Try block. bugid: 623 | ```c#
#if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using UnitDriven;
namespace Csla.Test.Silverlight.Rollback
{
#if SILVERLIGHT
[TestClass]
#endif
public class RollbackTests : TestBase
{
#if SILVERLIGHT
[TestMethod]
public void UnintializedProperty_RollsBack_AfterCancelEdit()
{
var context = GetContext();
RollbackRoot.BeginCreateLocal((o, e) =>
{
context.Assert.Try(() =>
{
var item = e.Object;
var initialValue = 0;// item.UnInitedP;
item.BeginEdit();
item.UnInitedP = 1000;
item.Another = "test";
item.CancelEdit();
context.Assert.AreEqual(initialValue, item.UnInitedP);
context.Assert.Success();
});
});
context.Complete();
}
#endif
}
}
``` |
654a6dcf-53a4-447a-b247-eb001a4a09b8 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.InteropServices;
namespace LibGPhoto2
{
public class Context : Object
{
[DllImport ("libgphoto2.so")]
internal static extern IntPtr gp_context_new ();
public Context ()
{
this.handle = new HandleRef (this, gp_context_new ());
}
[DllImport ("libgphoto2.so")]
internal static extern void gp_context_unref (HandleRef context);
protected override void Cleanup ()
{
System.Console.WriteLine ("cleanup context");
gp_context_unref(handle);
}
}
}
```
Remove random context cleanup console output | ```c#
using System;
using System.Runtime.InteropServices;
namespace LibGPhoto2
{
public class Context : Object
{
[DllImport ("libgphoto2.so")]
internal static extern IntPtr gp_context_new ();
public Context ()
{
this.handle = new HandleRef (this, gp_context_new ());
}
[DllImport ("libgphoto2.so")]
internal static extern void gp_context_unref (HandleRef context);
protected override void Cleanup ()
{
gp_context_unref(handle);
}
}
}
``` |
ce68da9c-322c-496a-9296-6c133ed1a59e | {
"language": "C#"
} | ```c#
// Copyright 2019 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
namespace VDrumExplorer.Data.Fields
{
public interface IField
{
string Description { get; }
FieldPath Path { get; }
ModuleAddress Address { get; }
int Size { get; }
public FieldCondition? Condition { get; }
}
}
```
Remove redundant specification of public in interface | ```c#
// Copyright 2019 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
namespace VDrumExplorer.Data.Fields
{
public interface IField
{
string Description { get; }
FieldPath Path { get; }
ModuleAddress Address { get; }
int Size { get; }
FieldCondition? Condition { get; }
}
}
``` |
e63007a5-b60d-495f-a865-9e92199f47fb | {
"language": "C#"
} | ```c#
using JetBrains.Annotations;
using PlayGroups.Input;
using UI;
using UnityEngine;
public class MessageOnInteract : InputTrigger
{
public string Message;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public override void Interact(GameObject originator, Vector3 position, string hand)
{
UIManager.Chat.AddChatEvent(new ChatEvent(Message, ChatChannel.Examine));
}
}
```
Use ChatRelay instead of UIManager when examining objects | ```c#
using JetBrains.Annotations;
using PlayGroups.Input;
using UI;
using UnityEngine;
public class MessageOnInteract : InputTrigger
{
public string Message;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public override void Interact(GameObject originator, Vector3 position, string hand)
{
ChatRelay.Instance.AddToChatLogClient(Message, ChatChannel.Examine);
}
}
``` |
b939758b-c5f9-46f9-babf-86329ab9b6b6 | {
"language": "C#"
} | ```c#
namespace StackExchange.Exceptional.Internal
{
/// <summary>
/// Internal Exceptional static controls, not meant for consumption.
/// This can and probably will break without warning. Don't use the .Internal namespace directly.
/// </summary>
public static class Statics
{
/// <summary>
/// Settings for context-less logging.
/// </summary>
/// <remarks>
/// In ASP.NET (non-Core) this is populated by the ConfigSettings load.
/// In ASP.NET Core this is populated by .Configure() in the DI pipeline.
/// </remarks>
public static ExceptionalSettingsBase Settings { get; set; }
/// <summary>
/// Returns whether an error passed in right now would be logged.
/// </summary>
public static bool IsLoggingEnabled { get; set; } = true;
}
}
```
Make sure Settings is never null | ```c#
namespace StackExchange.Exceptional.Internal
{
/// <summary>
/// Internal Exceptional static controls, not meant for consumption.
/// This can and probably will break without warning. Don't use the .Internal namespace directly.
/// </summary>
public static class Statics
{
/// <summary>
/// Settings for context-less logging.
/// </summary>
/// <remarks>
/// In ASP.NET (non-Core) this is populated by the ConfigSettings load.
/// In ASP.NET Core this is populated by .Configure() in the DI pipeline.
/// </remarks>
public static ExceptionalSettingsBase Settings { get; set; } = new ExceptionalSettingsDefault();
/// <summary>
/// Returns whether an error passed in right now would be logged.
/// </summary>
public static bool IsLoggingEnabled { get; set; } = true;
}
}
``` |
868a0aae-428d-4028-b619-963d65d17038 | {
"language": "C#"
} | ```c#
namespace Mappy
{
using System;
using System.ComponentModel;
using System.Reactive.Linq;
using System.Reactive.Subjects;
public static class ExtensionMethods
{
public static IObservable<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged
{
var subject = new BehaviorSubject<TField>(accessor(source));
// FIXME: This is leaky.
// We create a subscription to connect this to the subject
// but we don't hold onto this subscription.
// The subject we return can never be garbage collected
// because the subscription cannot be freed.
Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
x => source.PropertyChanged += x,
x => source.PropertyChanged -= x)
.Where(x => x.EventArgs.PropertyName == name)
.Select(_ => accessor(source))
.Subscribe(subject);
return subject;
}
}
}
```
Use multicast instead of explicit BehaviourSubject setup | ```c#
namespace Mappy
{
using System;
using System.ComponentModel;
using System.Reactive.Linq;
using System.Reactive.Subjects;
public static class ExtensionMethods
{
public static IObservable<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged
{
var obs = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
x => source.PropertyChanged += x,
x => source.PropertyChanged -= x)
.Where(x => x.EventArgs.PropertyName == name)
.Select(_ => accessor(source))
.Multicast(new BehaviorSubject<TField>(accessor(source)));
// FIXME: This is leaky.
// We create a connection here but don't hold on to the reference.
// We can never unregister our event handler without this.
obs.Connect();
return obs;
}
}
}
``` |
aba5a094-ee8c-4ae5-b342-facfd3ffd5c5 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TirkxDownloader.Framework.Interface
{
/// <summary>
/// This interface should be implemented for recieve JSON then parse it and return to caller
/// </summary>
/// <typeparam name="T">Type of message, must be JSON compatibility</typeparam>
interface IMessageReciever<T>
{
ICollection<string> Prefixes { get; }
bool IsRecieving { get; }
Task<T> GetMessageAsync();
/// <summary>
/// Call this method when terminate application
/// </summary>
void Close();
/// <summary>
/// Call this method when you want to stop reciever
/// </summary>
void StopReciever();
}
}
```
Delete stop reciever, to stop receiver use CancellationToken | ```c#
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TirkxDownloader.Framework.Interface
{
/// <summary>
/// This interface should be implemented for recieve JSON then parse it and return to caller
/// </summary>
/// <typeparam name="T">Type of message, must be JSON compatibility</typeparam>
public interface IMessageReciever<T>
{
ICollection<string> Prefixes { get; }
bool IsRecieving { get; }
Task<T> GetMessageAsync();
Task<T> GetMessageAsync(CancellationToken ct);
/// <summary>
/// Call this method when terminate application
/// </summary>
void Close();
}
}
``` |
b9a01809-0be8-4f88-9ecd-f31a96559d99 | {
"language": "C#"
} | ```c#
#if NULLABLE_SHIMS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
public sealed class MaybeNullWhenAttribute : Attribute
{
public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; }
public bool ReturnValue { get; }
}
}
#endif
```
Change MaybeNullWhenAttribute to internal to remove collision with diagnostics ns | ```c#
#if NULLABLE_SHIMS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class MaybeNullWhenAttribute : Attribute
{
public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; }
public bool ReturnValue { get; }
}
}
#endif
``` |
a5b1d5ea-4ed0-44ff-87de-574045617249 | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Framework.Configuration;
namespace Microsoft.AspNet.Server.Kestrel
{
public class ServerInformation : IServerInformation, IKestrelServerInformation
{
public ServerInformation()
{
Addresses = new List<ServerAddress>();
}
public void Initialize(IConfiguration configuration)
{
var urls = configuration["server.urls"];
if (!string.IsNullOrEmpty(urls))
{
urls = "http://+:5000/";
}
foreach (var url in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
var address = ServerAddress.FromUrl(url);
if (address != null)
{
Addresses.Add(address);
}
}
}
public string Name
{
get
{
return "Kestrel";
}
}
public IList<ServerAddress> Addresses { get; private set; }
public int ThreadCount { get; set; }
}
}
```
Fix regression in reading config | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Framework.Configuration;
namespace Microsoft.AspNet.Server.Kestrel
{
public class ServerInformation : IServerInformation, IKestrelServerInformation
{
public ServerInformation()
{
Addresses = new List<ServerAddress>();
}
public void Initialize(IConfiguration configuration)
{
var urls = configuration["server.urls"];
if (string.IsNullOrEmpty(urls))
{
urls = "http://+:5000/";
}
foreach (var url in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
var address = ServerAddress.FromUrl(url);
if (address != null)
{
Addresses.Add(address);
}
}
}
public string Name
{
get
{
return "Kestrel";
}
}
public IList<ServerAddress> Addresses { get; private set; }
public int ThreadCount { get; set; }
}
}
``` |
ceb56161-9dc8-4412-8341-666b3a9efb2e | {
"language": "C#"
} | ```c#
using System;
using Pdelvo.Minecraft.Network;
namespace Pdelvo.Minecraft.Protocol.Packets
{
[PacketUsage(PacketUsage.ServerToClient)]
public class DisplayScoreboard : Packet
{
public byte Position { get; set; }
public string ScoreName { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DisplayScoreboard" /> class.
/// </summary>
/// <remarks>
/// </remarks>
public DisplayScoreboard()
{
Code = 0xCF;
}
/// <summary>
/// Receives the specified reader.
/// </summary>
/// <param name="reader"> The reader. </param>
/// <param name="version"> The version. </param>
/// <remarks>
/// </remarks>
protected override void OnReceive(BigEndianStream reader, int version)
{
if (reader == null)
throw new ArgumentNullException("reader");
Position = reader.ReadByte();
ScoreName = reader.ReadString16();
}
/// <summary>
/// Sends the specified writer.
/// </summary>
/// <param name="writer"> The writer. </param>
/// <param name="version"> The version. </param>
/// <remarks>
/// </remarks>
protected override void OnSend(BigEndianStream writer, int version)
{
if (writer == null)
throw new ArgumentNullException("writer");
writer.Write(Code);
writer.Write(Position);
writer.Write(ScoreName);
}
}
}
```
Fix display scoreboard packet id | ```c#
using System;
using Pdelvo.Minecraft.Network;
namespace Pdelvo.Minecraft.Protocol.Packets
{
[PacketUsage(PacketUsage.ServerToClient)]
public class DisplayScoreboard : Packet
{
public byte Position { get; set; }
public string ScoreName { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DisplayScoreboard" /> class.
/// </summary>
/// <remarks>
/// </remarks>
public DisplayScoreboard()
{
Code = 0xD0;
}
/// <summary>
/// Receives the specified reader.
/// </summary>
/// <param name="reader"> The reader. </param>
/// <param name="version"> The version. </param>
/// <remarks>
/// </remarks>
protected override void OnReceive(BigEndianStream reader, int version)
{
if (reader == null)
throw new ArgumentNullException("reader");
Position = reader.ReadByte();
ScoreName = reader.ReadString16();
}
/// <summary>
/// Sends the specified writer.
/// </summary>
/// <param name="writer"> The writer. </param>
/// <param name="version"> The version. </param>
/// <remarks>
/// </remarks>
protected override void OnSend(BigEndianStream writer, int version)
{
if (writer == null)
throw new ArgumentNullException("writer");
writer.Write(Code);
writer.Write(Position);
writer.Write(ScoreName);
}
}
}
``` |
aee4d5da-9730-409f-a591-fc3b726af501 | {
"language": "C#"
} | ```c#
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ForecastPCL")]
[assembly: AssemblyDescription("An unofficial PCL for the forecast.io weather API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Cheng")]
[assembly: AssemblyProduct("ForecastPCL")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.4.0.0")]
[assembly: AssemblyFileVersion("2.4.0.0")]
```
Bump assembly version to 2.5.0. | ```c#
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ForecastPCL")]
[assembly: AssemblyDescription("An unofficial PCL for the forecast.io weather API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Cheng")]
[assembly: AssemblyProduct("ForecastPCL")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.5.0.0")]
[assembly: AssemblyFileVersion("2.5.0.0")]
``` |
58f28d5c-5606-4729-9bee-f08c4fd412c6 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.InteropServices;
using Foundation;
// Generated by Objective Sharpie (https://download.xamarin.com/objective-sharpie/ObjectiveSharpie.pkg)
// > sharpie bind -output TestFairy -namespace TestFairyLib -sdk iphoneos10.1 TestFairy.h
namespace TestFairyLib
{
public static class CFunctions
{
// extern void TFLog (NSString *format, ...) __attribute__((format(NSString, 1, 2)));
[DllImport ("__Internal")]
public static extern void TFLog (NSString format, IntPtr varArgs);
// extern void TFLogv (NSString *format, va_list arg_list);
[DllImport ("__Internal")]
public static extern unsafe void TFLogv (NSString format, sbyte* arg_list);
}
}
```
Use native pointer for format string | ```c#
using System;
using System.Runtime.InteropServices;
using Foundation;
// Generated by Objective Sharpie (https://download.xamarin.com/objective-sharpie/ObjectiveSharpie.pkg)
// > sharpie bind -output TestFairy -namespace TestFairyLib -sdk iphoneos10.1 TestFairy.h
namespace TestFairyLib
{
public static class CFunctions
{
// extern void TFLog (NSString *format, ...) __attribute__((format(NSString, 1, 2)));
[DllImport ("__Internal")]
public static extern void TFLog (IntPtr format, string arg0);
// extern void TFLogv (NSString *format, va_list arg_list);
[DllImport ("__Internal")]
public static extern unsafe void TFLogv (IntPtr format, sbyte* arg_list);
}
}
``` |
c82e7c18-2b1b-41e4-8f05-50408920e639 | {
"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.IO;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
using osu.Framework.Extensions.EnumExtensions;
namespace osu.Framework.Graphics.UserInterface
{
public abstract class DirectorySelectorDirectory : DirectorySelectorItem
{
protected readonly DirectoryInfo Directory;
protected override string FallbackName => Directory.Name;
[Resolved]
private Bindable<DirectoryInfo> currentDirectory { get; set; }
protected DirectorySelectorDirectory(DirectoryInfo directory, string displayName = null)
: base(displayName)
{
Directory = directory;
try
{
bool isHidden = directory?.Attributes.HasFlagFast(FileAttributes.Hidden) == true;
// On Windows, system drives are returned with `System | Hidden | Directory` file attributes,
// but the expectation is that they shouldn't be shown in a hidden state.
bool isSystemDrive = directory?.Parent == null;
if (isHidden && !isSystemDrive)
ApplyHiddenState();
}
catch (UnauthorizedAccessException)
{
// checking attributes on access-controlled directories will throw an error so we handle it here to prevent a crash
}
}
protected override bool OnClick(ClickEvent e)
{
currentDirectory.Value = Directory;
return true;
}
}
}
```
Fix directory selector crashing when attempting to display a bitlocker locked drive | ```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.IO;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
using osu.Framework.Extensions.EnumExtensions;
namespace osu.Framework.Graphics.UserInterface
{
public abstract class DirectorySelectorDirectory : DirectorySelectorItem
{
protected readonly DirectoryInfo Directory;
protected override string FallbackName => Directory.Name;
[Resolved]
private Bindable<DirectoryInfo> currentDirectory { get; set; }
protected DirectorySelectorDirectory(DirectoryInfo directory, string displayName = null)
: base(displayName)
{
Directory = directory;
try
{
bool isHidden = directory?.Attributes.HasFlagFast(FileAttributes.Hidden) == true;
// On Windows, system drives are returned with `System | Hidden | Directory` file attributes,
// but the expectation is that they shouldn't be shown in a hidden state.
bool isSystemDrive = directory?.Parent == null;
if (isHidden && !isSystemDrive)
ApplyHiddenState();
}
catch (IOException)
{
// various IO exceptions could occur when attempting to read attributes.
// one example is when a target directory is a drive which is locked by BitLocker:
//
// "Unhandled exception. System.IO.IOException: This drive is locked by BitLocker Drive Encryption. You must unlock this drive from Control Panel. : 'D:\'"
}
catch (UnauthorizedAccessException)
{
// checking attributes on access-controlled directories will throw an error so we handle it here to prevent a crash
}
}
protected override bool OnClick(ClickEvent e)
{
currentDirectory.Value = Directory;
return true;
}
}
}
``` |
676bc0cc-1e23-4436-9774-e986eae19f61 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace PinSharp.Http
{
internal class FormUrlEncodedContent : ByteArrayContent
{
private static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding("ISO-8859-1");
public FormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
: base(GetContentByteArray(nameValueCollection))
{
Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}
private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
{
if (nameValueCollection == null) throw new ArgumentNullException(nameof(nameValueCollection));
var stringBuilder = new StringBuilder();
foreach (var keyValuePair in nameValueCollection)
{
if (stringBuilder.Length > 0)
stringBuilder.Append('&');
stringBuilder.Append(Encode(keyValuePair.Key));
stringBuilder.Append('=');
stringBuilder.Append(Encode(keyValuePair.Value));
}
return DefaultHttpEncoding.GetBytes(stringBuilder.ToString());
}
private static string Encode(string data)
{
return string.IsNullOrEmpty(data) ? "" : Uri.EscapeDataString(data).Replace("%20", "+");
}
}
}
```
Fix issue with long data string (e.g. base64) | ```c#
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace PinSharp.Http
{
internal class FormUrlEncodedContent : ByteArrayContent
{
private static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding("ISO-8859-1");
public FormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
: base(GetContentByteArray(nameValueCollection))
{
Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}
private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
{
if (nameValueCollection == null) throw new ArgumentNullException(nameof(nameValueCollection));
var stringBuilder = new StringBuilder();
foreach (var keyValuePair in nameValueCollection)
{
if (stringBuilder.Length > 0)
stringBuilder.Append('&');
stringBuilder.Append(Encode(keyValuePair.Key));
stringBuilder.Append('=');
stringBuilder.Append(Encode(keyValuePair.Value));
}
return DefaultHttpEncoding.GetBytes(stringBuilder.ToString());
}
private static string Encode(string data)
{
if (string.IsNullOrEmpty(data))
return "";
return EscapeLongDataString(data);
}
private static string EscapeLongDataString(string data)
{
// Uri.EscapeDataString() does not support strings longer than this
const int maxLength = 65519;
var sb = new StringBuilder();
var iterationsNeeded = data.Length / maxLength;
for (var i = 0; i <= iterationsNeeded; i++)
{
sb.Append(i < iterationsNeeded
? Uri.EscapeDataString(data.Substring(maxLength * i, maxLength))
: Uri.EscapeDataString(data.Substring(maxLength * i)));
}
return sb.ToString().Replace("%20", "+");
}
}
}
``` |
1dfe8885-d7ad-4008-84ff-360c6a3c6c22 | {
"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.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
```
Increment build number to match NuGet | ```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.1")]
[assembly: AssemblyFileVersion("1.1.0.1")]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.