doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
a94402e4-1d90-48d9-b2df-514441f10629
{ "language": "C#" }
```c# using System.Collections.Generic; using Newtonsoft.Json; namespace Stripe { public class StripePlanUpdateOptions : StripeBaseOptions, ISupportMetadata { [JsonProperty("active")] public bool? Active { get; set; } [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } [JsonProperty("nickname")] public string Nickname { get; set; } } } ``` Add support for `product` on the Plan Update API
```c# using System.Collections.Generic; using Newtonsoft.Json; namespace Stripe { public class StripePlanUpdateOptions : StripeBaseOptions, ISupportMetadata { [JsonProperty("active")] public bool? Active { get; set; } [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } [JsonProperty("nickname")] public string Nickname { get; set; } [JsonProperty("product")] public string ProductId { get; set; } } } ```
1c91e15e-b368-41b6-8791-cf82e904bca9
{ "language": "C#" }
```c# using System; using CefSharp.BrowserSubprocess; namespace TweetDuck.Browser{ static class Program{ internal const string Version = "1.4.1.0"; private static int Main(string[] args){ SubProcess.EnableHighDPISupport(); const string typePrefix = "--type="; string type = Array.Find(args, arg => arg.StartsWith(typePrefix, StringComparison.OrdinalIgnoreCase)).Substring(typePrefix.Length); if (type == "renderer"){ using(SubProcess subProcess = new SubProcess(args)){ return subProcess.Run(); } } else{ return SubProcess.ExecuteProcess(); } } } } ``` Kill subprocess if it doesn't exit after the app is closed
```c# using System; using System.Diagnostics; using System.Threading.Tasks; using CefSharp.BrowserSubprocess; namespace TweetDuck.Browser{ static class Program{ internal const string Version = "1.4.1.0"; private static int Main(string[] args){ SubProcess.EnableHighDPISupport(); string FindArg(string key){ return Array.Find(args, arg => arg.StartsWith(key, StringComparison.OrdinalIgnoreCase)).Substring(key.Length); } const string typePrefix = "--type="; const string parentIdPrefix = "--host-process-id="; if (!int.TryParse(FindArg(parentIdPrefix), out int parentId)){ return 0; } Task.Factory.StartNew(() => KillWhenHung(parentId), TaskCreationOptions.LongRunning); if (FindArg(typePrefix) == "renderer"){ using(SubProcess subProcess = new SubProcess(args)){ return subProcess.Run(); } } else{ return SubProcess.ExecuteProcess(); } } private static async void KillWhenHung(int parentId){ try{ using(Process process = Process.GetProcessById(parentId)){ process.WaitForExit(); } }catch{ // ded } await Task.Delay(10000); Environment.Exit(0); } } } ```
eb120abc-8320-4ce5-9a2b-aa7cb2ba5725
{ "language": "C#" }
```c# using RimWorld; using Verse; namespace PrepareLanding.Defs { /// <summary> /// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing /// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml"). /// </summary> public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld { public override void Activate() { // default behavior (go to the world map) base.Activate(); // do not show the main window if in tutorial mode if (TutorSystem.TutorialMode) { Log.Message( "[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window."); return; } // don't add a new window if the window is already there; if it's not create a new one. if (PrepareLanding.Instance.MainWindow == null) PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData); // show the main window, minimized. PrepareLanding.Instance.MainWindow.Show(true); } } } ``` Fix comment about the patch path.
```c# using RimWorld; using Verse; namespace PrepareLanding.Defs { /// <summary> /// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing /// (see "\PrepareLanding\Patches\MainButtonDef_Patch.xml"). /// </summary> public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld { public override void Activate() { // default behavior (go to the world map) base.Activate(); // do not show the main window if in tutorial mode if (TutorSystem.TutorialMode) { Log.Message( "[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window."); return; } // don't add a new window if the window is already there; if it's not create a new one. if (PrepareLanding.Instance.MainWindow == null) PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData); // show the main window, minimized. PrepareLanding.Instance.MainWindow.Show(true); } } } ```
b0065bbc-e774-4d8e-8103-8bd7857bc15d
{ "language": "C#" }
```c# using System.Linq; using ZobShop.Data.Contracts; using ZobShop.Factories; using ZobShop.Models; using ZobShop.Services.Contracts; namespace ZobShop.Services { public class CategoryService : ICategoryService { private readonly IRepository<Category> repository; private readonly IUnitOfWork unitOfWork; private readonly ICategoryFactory factory; public CategoryService(IRepository<Category> repository, IUnitOfWork unitOfWork, ICategoryFactory factory) { this.repository = repository; this.unitOfWork = unitOfWork; this.factory = factory; } public Category GetCategoryByName(string name) { var category = this.repository .GetAll((Category c) => c.Name == name) .FirstOrDefault(); return category; } public Category CreateCategory(string name) { var category = this.factory.CreateCategory(name); this.repository.Add(category); this.unitOfWork.Commit(); return category; } } } ``` Add category service constructor validation
```c# using System; using System.Linq; using ZobShop.Data.Contracts; using ZobShop.Factories; using ZobShop.Models; using ZobShop.Services.Contracts; namespace ZobShop.Services { public class CategoryService : ICategoryService { private readonly IRepository<Category> repository; private readonly IUnitOfWork unitOfWork; private readonly ICategoryFactory factory; public CategoryService(IRepository<Category> repository, IUnitOfWork unitOfWork, ICategoryFactory factory) { if (repository == null) { throw new ArgumentNullException("repository cannot be null"); } if (factory == null) { throw new ArgumentNullException("factory cannot be null"); } if (unitOfWork == null) { throw new ArgumentNullException("unit of work cannot be null"); } this.repository = repository; this.unitOfWork = unitOfWork; this.factory = factory; } public Category GetCategoryByName(string name) { var category = this.repository .GetAll((Category c) => c.Name == name) .FirstOrDefault(); return category; } public Category CreateCategory(string name) { var category = this.factory.CreateCategory(name); this.repository.Add(category); this.unitOfWork.Commit(); return category; } } } ```
8cb3386d-3b41-4dc6-9184-e24fdf0e9a35
{ "language": "C#" }
```c# using InEngine.Core; namespace InEngine.Commands { /// <summary> /// Dummy command for testing and sample code. /// </summary> public class AlwaysSucceed : AbstractCommand { public override void Run() { Info("Ths command always succeeds."); } } } ``` Fix typo in succeed command output
```c# using InEngine.Core; namespace InEngine.Commands { /// <summary> /// Dummy command for testing and sample code. /// </summary> public class AlwaysSucceed : AbstractCommand { public override void Run() { Info("This command always succeeds."); } } } ```
56d67f18-1e0c-4999-84d2-b864d0300dfb
{ "language": "C#" }
```c# using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia; using Avalonia.Input; using ReactiveUI; using System.Reactive.Linq; using System; namespace WalletWasabi.Gui.Controls.LockScreen { public class PinLockScreen : UserControl { public static readonly DirectProperty<PinLockScreen, bool> IsLockedProperty = AvaloniaProperty.RegisterDirect<PinLockScreen, bool>(nameof(IsLocked), o => o.IsLocked, (o, v) => o.IsLocked = v); private bool _isLocked; public bool IsLocked { get => _isLocked; set => SetAndRaise(IsLockedProperty, ref _isLocked, value); } public PinLockScreen() : base() { InitializeComponent(); var inputField = this.FindControl<NoparaPasswordBox>("InputField"); this.WhenAnyValue(x => x.IsLocked) .Where(x => x) .Subscribe(x => inputField.Focus()); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } } ``` Set the focus of passwordbox after app start.
```c# using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia; using Avalonia.Input; using ReactiveUI; using System.Reactive.Linq; using System; using Avalonia.LogicalTree; namespace WalletWasabi.Gui.Controls.LockScreen { public class PinLockScreen : UserControl { public static readonly DirectProperty<PinLockScreen, bool> IsLockedProperty = AvaloniaProperty.RegisterDirect<PinLockScreen, bool>(nameof(IsLocked), o => o.IsLocked, (o, v) => o.IsLocked = v); private bool _isLocked; public bool IsLocked { get => _isLocked; set => SetAndRaise(IsLockedProperty, ref _isLocked, value); } public PinLockScreen() : base() { InitializeComponent(); var inputField = this.FindControl<NoparaPasswordBox>("InputField"); this.WhenAnyValue(x => x.IsLocked) .Where(x => x) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => inputField.Focus()); } protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); // When the control first created on AppStart set the Focus of the password box. // If you just simply set the Focus without delay it won't work. Observable .Interval(TimeSpan.FromSeconds(1)) .Take(1) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => { var inputField = this.FindControl<NoparaPasswordBox>("InputField"); inputField.Focus(); }); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } } ```
3d81b634-952b-481f-afc9-b1651536d2ff
{ "language": "C#" }
```c# var octokit = Require<OctokitPack>(); var client = octokit.Create("ScriptCs.Octokit"); var userTask = client.User.Get("alfhenrik"); var user = userTask.Result; Console.WriteLine(user.Name); var repoTask = client.Repository.GetAllBranches("alfhenrik", "octokit.net"); var branches = repoTask.Result; Console.WriteLine(branches.Count); foreach(var branch in branches) { Console.WriteLine(branch.Name); }``` Fix integration test due to breaking change in latest Octokit.net release
```c# var octokit = Require<OctokitPack>(); var client = octokit.Create("ScriptCs.Octokit"); var userTask = client.User.Get("alfhenrik"); var user = userTask.Result; Console.WriteLine(user.Name); var repoTask = client.Repository.Branch.GetAll("alfhenrik", "octokit.net"); var branches = repoTask.Result; Console.WriteLine(branches.Count); foreach(var branch in branches) { Console.WriteLine(branch.Name); }```
36a740d5-d0b6-43e1-b5a8-4d1c9db7d635
{ "language": "C#" }
```c# using System; namespace Mocca { public class MoccaCompiler { public MoccaCompiler() { } } } ``` Add Target Language, Compiler Interface
```c# using System; using System.Collections.Generic; using System.Text; using Mocca.DataType; namespace Mocca { public enum TargetLanguage { Python, // Now available Java, // NOT available Javascript, // NOT available C_sharp, // NOT available Swift // NOT Available } public interface Compiler { string compile(List<MoccaBlockGroup> source); } public class MoccaCompiler { List<MoccaBlockGroup> source; TargetLanguage lang; public MoccaCompiler(List<MoccaBlockGroup> source, TargetLanguage lang) { this.source = source; this.lang = lang; } } } ```
be2c83fe-cce1-4be8-a32b-8d0a70e6f639
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using JoinRpg.DataModel; namespace JoinRpg.Domain { public static class FieldExtensions { public static bool HasValueList(this ProjectField field) { return field.FieldType == ProjectFieldType.Dropdown || field.FieldType == ProjectFieldType.MultiSelect; } public static bool HasSpecialGroup(this ProjectField field) { return field.HasValueList() && field.FieldBoundTo == FieldBoundTo.Character; } public static IReadOnlyList<ProjectFieldDropdownValue> GetDropdownValues(this FieldWithValue field) { var value = field.GetSelectedIds(); return field.GetPossibleValues().Where( v => value.Contains(v.ProjectFieldDropdownValueId)).ToList().AsReadOnly(); } private static IEnumerable<int> GetSelectedIds(this FieldWithValue field) { return string.IsNullOrWhiteSpace(field.Value) ? Enumerable.Empty<int>() : field.Value.Split(',').Select(Int32.Parse); } public static IEnumerable<ProjectFieldDropdownValue> GetPossibleValues(this FieldWithValue field) => field.Field.GetOrderedValues(); public static string GetSpecialGroupName(this ProjectFieldDropdownValue fieldValue) { return $"{fieldValue.Label}"; } public static string GetSpecialGroupName(this ProjectField field) { return $"{field.FieldName}"; } } } ``` Hide already deleted variants if not set
```c# using System; using System.Collections.Generic; using System.Linq; using JoinRpg.DataModel; namespace JoinRpg.Domain { public static class FieldExtensions { public static bool HasValueList(this ProjectField field) { return field.FieldType == ProjectFieldType.Dropdown || field.FieldType == ProjectFieldType.MultiSelect; } public static bool HasSpecialGroup(this ProjectField field) { return field.HasValueList() && field.FieldBoundTo == FieldBoundTo.Character; } public static IReadOnlyList<ProjectFieldDropdownValue> GetDropdownValues(this FieldWithValue field) { var value = field.GetSelectedIds(); return field.GetPossibleValues().Where( v => value.Contains(v.ProjectFieldDropdownValueId)).ToList().AsReadOnly(); } private static IEnumerable<int> GetSelectedIds(this FieldWithValue field) { return string.IsNullOrWhiteSpace(field.Value) ? Enumerable.Empty<int>() : field.Value.Split(',').Select(int.Parse); } public static IEnumerable<ProjectFieldDropdownValue> GetPossibleValues(this FieldWithValue field) { var value = field.GetSelectedIds(); return field.Field.GetOrderedValues().Where(v => v.IsActive || value.Contains(v.ProjectFieldDropdownValueId)); } public static string GetSpecialGroupName(this ProjectFieldDropdownValue fieldValue) { return $"{fieldValue.Label}"; } public static string GetSpecialGroupName(this ProjectField field) { return $"{field.FieldName}"; } } } ```
ac0ff553-0c68-49d7-b4d1-a7720b983995
{ "language": "C#" }
```c#  namespace SettlersOfCatan.Mutable { public class Player { public Resources Hand { get; private set; } public Player() { Hand = new Resources(); } public void Trade(Player other, Resources give, Resources take) { Hand.RequireAtLeast(give); other.Hand.RequireAtLeast(take); Hand.Subtract(give); other.Hand.Add(give); Hand.Add(take); other.Hand.Subtract(take); } } } ``` Use getter only auto property for player resources.
```c#  namespace SettlersOfCatan.Mutable { public class Player { public Resources Hand { get; } public Player() { Hand = new Resources(); } public void Trade(Player other, Resources give, Resources take) { Hand.RequireAtLeast(give); other.Hand.RequireAtLeast(take); Hand.Subtract(give); other.Hand.Add(give); Hand.Add(take); other.Hand.Subtract(take); } } } ```
9d53f835-ccf3-461a-b33b-7a82bb1df9b3
{ "language": "C#" }
```c# using System.Data.Services; using System.ServiceModel.Activation; using System.Web.Routing; using NuGet.Server; using NuGet.Server.DataServices; using NuGet.Server.Publishing; using RouteMagic; [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyGet.NuGetRoutes), "Start")] namespace MyGet { public static class NuGetRoutes { public static void Start() { ServiceResolver.SetServiceResolver(new DefaultServiceResolver()); MapRoutes(RouteTable.Routes); } private static void MapRoutes(RouteCollection routes) { // Route to create a new package(http://{root}/nuget) routes.MapDelegate("CreatePackageNuGet", "nuget", new { httpMethod = new HttpMethodConstraint("PUT") }, context => CreatePackageService().CreatePackage(context.HttpContext)); // The default route is http://{root}/nuget/Packages var factory = new DataServiceHostFactory(); var serviceRoute = new ServiceRoute("nuget", factory, typeof(Packages)); serviceRoute.Defaults = new RouteValueDictionary { { "serviceType", "odata" } }; serviceRoute.Constraints = new RouteValueDictionary { { "serviceType", "odata" } }; routes.Add("nuget", serviceRoute); } private static IPackageService CreatePackageService() { return ServiceResolver.Resolve<IPackageService>(); } } } ``` Use default routes from package.
```c# using System.Data.Services; using System.ServiceModel.Activation; using System.Web.Routing; using NuGet.Server; using NuGet.Server.DataServices; using NuGet.Server.Publishing; using RouteMagic; [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyGet.NuGetRoutes), "Start")] namespace MyGet { public static class NuGetRoutes { public static void Start() { ServiceResolver.SetServiceResolver(new DefaultServiceResolver()); MapRoutes(RouteTable.Routes); } private static void MapRoutes(RouteCollection routes) { // Route to create a new package(http://{root}/nuget) routes.MapDelegate("CreatePackageNuGet", "nuget", new { httpMethod = new HttpMethodConstraint("PUT") }, context => CreatePackageService().CreatePackage(context.HttpContext)); // The default route is http://{root}/nuget/Packages var factory = new DataServiceHostFactory(); var serviceRoute = new ServiceRoute("nuget", factory, typeof(Packages)); serviceRoute.Defaults = new RouteValueDictionary { { "serviceType", "odata" } }; serviceRoute.Constraints = new RouteValueDictionary { { "serviceType", "odata" } }; routes.Add("nuget", serviceRoute); } private static IPackageService CreatePackageService() { return ServiceResolver.Resolve<IPackageService>(); } } } ```
227da4e9-d9aa-4e2f-9881-97e108b677aa
{ "language": "C#" }
```c# using System; namespace VGPrompter { public class Logger { public bool Enabled { get; set; } public string Name { get; private set; } Action<object> _logger; public Logger(bool enabled = true) : this("Default", enabled: enabled) { } public Logger(string name, Action<object> f = null, bool enabled = true) { Enabled = enabled; Name = name; _logger = f ?? Console.WriteLine; } public void Log(object s) { if (Enabled) _logger(s); } } }``` Fix regression in Script serialization
```c# using System; namespace VGPrompter { [Serializable] public class Logger { public bool Enabled { get; set; } public string Name { get; private set; } Action<object> _logger; public Logger(bool enabled = true) : this("Default", enabled: enabled) { } public Logger(string name, Action<object> f = null, bool enabled = true) { Enabled = enabled; Name = name; _logger = f ?? Console.WriteLine; } public void Log(object s) { if (Enabled) _logger(s); } } }```
89cf6bd3-54af-4f0b-b173-c9e348d2dd4f
{ "language": "C#" }
```c# using System; using System.Collections.Concurrent; using System.Linq; using KafkaNet.Model; using KafkaNet.Protocol; namespace KafkaNet { public class DefaultPartitionSelector : IPartitionSelector { private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>(); public Partition Select(Topic topic, string key) { if (topic == null) throw new ArgumentNullException("topic"); if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic)); //use round robing var partitions = topic.Partitions; if (key == null) { return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) => { var index = partitions.FindIndex(0, p => p.Equals(i)); if (index == -1) return partitions.First(); if (++index >= partitions.Count) return partitions.First(); return partitions[index]; }); } //use key hash var partitionId = key.GetHashCode() % partitions.Count; var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId); if (partition == null) throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}", partitionId, string.Join(",", partitions.Select(x => x.PartitionId)))); return partition; } } }``` Fix error in hash key selector would return -1
```c# using System; using System.Collections.Concurrent; using System.Linq; using KafkaNet.Model; using KafkaNet.Protocol; namespace KafkaNet { public class DefaultPartitionSelector : IPartitionSelector { private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>(); public Partition Select(Topic topic, string key) { if (topic == null) throw new ArgumentNullException("topic"); if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic)); //use round robing var partitions = topic.Partitions; if (key == null) { return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) => { var index = partitions.FindIndex(0, p => p.Equals(i)); if (index == -1) return partitions.First(); if (++index >= partitions.Count) return partitions.First(); return partitions[index]; }); } //use key hash var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count; var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId); if (partition == null) throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}", partitionId, string.Join(",", partitions.Select(x => x.PartitionId)))); return partition; } } }```
d8aa6f88-703f-4d8f-ae03-1bee7f95ede8
{ "language": "C#" }
```c# using KeyPay.DomainModels.V2.Business; using KeyPay.DomainModels.V2.Manager; using System.Collections.Generic; namespace KeyPay.ApiFunctions.V2 { public class ManagerFunction : BaseFunction { public ManagerFunction(ApiRequestExecutor api) : base(api) { LeaveRequests = new ManagerLeaveRequestsFunction(api); Kiosk = new ManagerKioskFunction(api); TimeAndAttendance = new ManagerTimeAndAttendanceFunction(api); } public ManagerLeaveRequestsFunction LeaveRequests { get; set; } public List<ManagerLeaveEmployeeModel> Employees(int businessId) { return ApiRequest<List<ManagerLeaveEmployeeModel>>($"/business/{businessId}/manager/employees"); } public List<LocationModel> Locations(int businessId) { return ApiRequest<List<LocationModel>>($"/business/{businessId}/manager/locations"); } public ManagerKioskFunction Kiosk { get; set; } public ManagerTimeAndAttendanceFunction TimeAndAttendance { get; set; } } }``` Include manager leave request functions and update to version 1.1.0.15-rc2
```c# using KeyPay.DomainModels.V2.Business; using KeyPay.DomainModels.V2.Manager; using System.Collections.Generic; namespace KeyPay.ApiFunctions.V2 { public class ManagerFunction : BaseFunction { public ManagerFunction(ApiRequestExecutor api) : base(api) { LeaveRequests = new ManagerLeaveRequestsFunction(api); Kiosk = new ManagerKioskFunction(api); TimeAndAttendance = new ManagerTimeAndAttendanceFunction(api); } public ManagerLeaveRequestsFunction LeaveRequests { get; set; } public ManagerKioskFunction Kiosk { get; set; } public ManagerTimeAndAttendanceFunction TimeAndAttendance { get; set; } public List<ManagerLeaveEmployeeModel> Employees(int businessId) { return ApiRequest<List<ManagerLeaveEmployeeModel>>($"/business/{businessId}/manager/employees"); } public List<LocationModel> Locations(int businessId) { return ApiRequest<List<LocationModel>>($"/business/{businessId}/manager/locations"); } } }```
7408d314-abf4-4b48-a617-cc91433e4fb8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Web; namespace MIMWebClient.Core.Update { public class UpdateWorld { public static void Init() { Task.Run(UpdateTime); } public static void CleanRoom() { Task.Run(UpdateRoom); } public static void UpdateMob() { Task.Run(MoveMob); } /// <summary> /// Wahoo! This works /// Now needs to update player/mob stats, spells, reset rooms and mobs. Move mobs around? /// Global Timer every 60 seconds? quicker timer for mob movement? /// </summary> /// <returns></returns> public static async Task UpdateTime() { Time.UpdateTIme(); Init(); } public static async Task UpdateRoom() { await Task.Delay(300000); HubContext.getHubContext.Clients.All.addNewMessageToPage("This is will update Rooms every 5 minutes and not block the game"); CleanRoom(); } public static async Task MoveMob() { //await Task.Delay(5000); //HubContext.getHubContext.Clients.All.addNewMessageToPage("This task will update Mobs every 5 seconds and not block the game"); //UpdateMob(); } } }``` Update Delay to 30 seconds
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Web; namespace MIMWebClient.Core.Update { public class UpdateWorld { public static void Init() { Task.Run(UpdateTime); } public static void CleanRoom() { Task.Run(UpdateRoom); } public static void UpdateMob() { Task.Run(MoveMob); } /// <summary> /// Wahoo! This works /// Now needs to update player/mob stats, spells, reset rooms and mobs. Move mobs around? /// Global Timer every 60 seconds? quicker timer for mob movement? /// </summary> /// <returns></returns> public static async Task UpdateTime() { await Task.Delay(30000); Time.UpdateTIme(); Init(); } public static async Task UpdateRoom() { await Task.Delay(300000); HubContext.getHubContext.Clients.All.addNewMessageToPage("This is will update Rooms every 5 minutes and not block the game"); CleanRoom(); } public static async Task MoveMob() { //await Task.Delay(5000); //HubContext.getHubContext.Clients.All.addNewMessageToPage("This task will update Mobs every 5 seconds and not block the game"); //UpdateMob(); } } }```
37e64a90-2ddb-4032-82ab-6c8d47e38257
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrefabsPool : GameObjectBehavior { public Dictionary<string, GameObject> prefabs; // Only one ObjectPoolManager can exist. We use a singleton pattern to enforce this. private static PrefabsPool _instance = null; public static PrefabsPool instance { get { if (!_instance) { _instance = FindObjectOfType(typeof(PrefabsPool)) as PrefabsPool; if (!_instance) { var obj = new GameObject("_PrefabsPool"); _instance = obj.AddComponent<PrefabsPool>(); } } return _instance; } } private void OnApplicationQuit() { _instance = null; } public static void CheckPrefabs() { if(instance == null) { return; } if(instance.prefabs == null) { instance.prefabs = new Dictionary<string, GameObject>(); } } public static GameObject PoolPrefab(string path) { if(instance == null) { return null; } CheckPrefabs(); string key = CryptoUtil.CalculateSHA1ASCII(path); if(!instance.prefabs.ContainsKey(key)) { GameObject prefab = Resources.Load(path) as GameObject; if(prefab != null) { instance.prefabs.Add(key, Resources.Load(path) as GameObject); } } if(instance.prefabs.ContainsKey(key)) { return instance.prefabs[key]; } return null; } } ``` Update prefabs resources.load flow, fix dual load.
```c# using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrefabsPool : GameObjectBehavior { public Dictionary<string, GameObject> prefabs; // Only one ObjectPoolManager can exist. We use a singleton pattern to enforce this. private static PrefabsPool _instance = null; public static PrefabsPool instance { get { if (!_instance) { _instance = FindObjectOfType(typeof(PrefabsPool)) as PrefabsPool; if (!_instance) { var obj = new GameObject("_PrefabsPool"); _instance = obj.AddComponent<PrefabsPool>(); } } return _instance; } } private void OnApplicationQuit() { _instance = null; } public static void CheckPrefabs() { if(instance == null) { return; } if(instance.prefabs == null) { instance.prefabs = new Dictionary<string, GameObject>(); } } public static GameObject PoolPrefab(string path) { if(instance == null) { return null; } CheckPrefabs(); string key = CryptoUtil.CalculateSHA1ASCII(path); if(!instance.prefabs.ContainsKey(key)) { GameObject prefab = Resources.Load(path) as GameObject; if(prefab != null) { instance.prefabs.Add(key, prefab); } } if(instance.prefabs.ContainsKey(key)) { return instance.prefabs[key]; } return null; } } ```
ae0b18d2-c132-4e13-9edc-7d4dbb552709
{ "language": "C#" }
```c# using System; using System.Net; using BmpListener.Bmp; using BmpListener.JSON; using Newtonsoft.Json; namespace BmpListener { internal class Program { private static void Main() { JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new TestConverter()); return settings; }; var ip = IPAddress.Parse("192.168.1.126"); var bmpListener = new BmpListener(ip); bmpListener.Start(WriteJson).Wait(); } private static void WriteJson(BmpMessage msg) { var json = JsonConvert.SerializeObject(msg); Console.WriteLine(json); } } }``` Change default behaviour to listen on all IP addresses
```c# using System; using System.Net; using BmpListener.Bmp; using BmpListener.JSON; using Newtonsoft.Json; namespace BmpListener { internal class Program { private static void Main() { JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new TestConverter()); return settings; }; var bmpListener = new BmpListener(); bmpListener.Start(WriteJson).Wait(); } private static void WriteJson(BmpMessage msg) { var json = JsonConvert.SerializeObject(msg); Console.WriteLine(json); } } }```
1467b79d-f030-4734-be74-f3b431b19cee
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Realms; #nullable enable namespace osu.Game.Database { /// <summary> /// Provides a method of working with unmanaged realm objects. /// Usually used for testing purposes where the instance is never required to be managed. /// </summary> /// <typeparam name="T">The underlying object type.</typeparam> public class RealmLiveUnmanaged<T> : ILive<T> where T : RealmObjectBase, IHasGuidPrimaryKey { /// <summary> /// Construct a new instance of live realm data. /// </summary> /// <param name="data">The realm data.</param> public RealmLiveUnmanaged(T data) { Value = data; } public bool Equals(ILive<T>? other) => ID == other?.ID; public Guid ID => Value.ID; public void PerformRead(Action<T> perform) => perform(Value); public TReturn PerformRead<TReturn>(Func<T, TReturn> perform) => perform(Value); public void PerformWrite(Action<T> perform) => throw new InvalidOperationException(@"Can't perform writes on a non-managed underlying value"); public bool IsManaged => false; /// <summary> /// The original live data used to create this instance. /// </summary> public T Value { get; } } } ``` Fix "Random Skin" text not showing up correctly
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Realms; #nullable enable namespace osu.Game.Database { /// <summary> /// Provides a method of working with unmanaged realm objects. /// Usually used for testing purposes where the instance is never required to be managed. /// </summary> /// <typeparam name="T">The underlying object type.</typeparam> public class RealmLiveUnmanaged<T> : ILive<T> where T : RealmObjectBase, IHasGuidPrimaryKey { /// <summary> /// Construct a new instance of live realm data. /// </summary> /// <param name="data">The realm data.</param> public RealmLiveUnmanaged(T data) { Value = data; } public bool Equals(ILive<T>? other) => ID == other?.ID; public override string ToString() => Value.ToString(); public Guid ID => Value.ID; public void PerformRead(Action<T> perform) => perform(Value); public TReturn PerformRead<TReturn>(Func<T, TReturn> perform) => perform(Value); public void PerformWrite(Action<T> perform) => throw new InvalidOperationException(@"Can't perform writes on a non-managed underlying value"); public bool IsManaged => false; /// <summary> /// The original live data used to create this instance. /// </summary> public T Value { get; } } } ```
ed6f93f4-48b4-4abf-bdc4-14bb07c2e36e
{ "language": "C#" }
```c# using System; namespace GitIStage { internal sealed class ConsoleCommand { private readonly Action _handler; private readonly ConsoleKey _key; public readonly string Description; private readonly ConsoleModifiers _modifiers; public ConsoleCommand(Action handler, ConsoleKey key, string description) { _handler = handler; _key = key; Description = description; _modifiers = 0; } public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description) { _handler = handler; _key = key; _modifiers = modifiers; Description = description; } public void Execute() { _handler(); } public bool MatchesKey(ConsoleKeyInfo keyInfo) { return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers; } public string GetCommandShortcut() { string key = _key.ToString().Replace("Arrow", ""); if (_modifiers != 0) { return $"{_modifiers.ToString().Replace("Control", "CTRL")} + {key.ToString()}"; } else return key.ToString(); } } }``` Change CTRL to Ctrl in commands description.
```c# using System; namespace GitIStage { internal sealed class ConsoleCommand { private readonly Action _handler; private readonly ConsoleKey _key; public readonly string Description; private readonly ConsoleModifiers _modifiers; public ConsoleCommand(Action handler, ConsoleKey key, string description) { _handler = handler; _key = key; Description = description; _modifiers = 0; } public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description) { _handler = handler; _key = key; _modifiers = modifiers; Description = description; } public void Execute() { _handler(); } public bool MatchesKey(ConsoleKeyInfo keyInfo) { return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers; } public string GetCommandShortcut() { string key = _key.ToString().Replace("Arrow", ""); if (_modifiers != 0) { return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}"; } else return key.ToString(); } } } ```
c99187e4-0a03-4d73-9c28-aa9cf3dc65d7
{ "language": "C#" }
```c# namespace DD.CBU.Compute.Api.Contracts.Backup { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://oec.api.opsource.net/schemas/backup")] public enum ServicePlan { /// <remarks/> Essentials, /// <remarks/> Advanced, /// <remarks/> Enterprise, } }``` Change default backup service plan enum value.
```c# namespace DD.CBU.Compute.Api.Contracts.Backup { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://oec.api.opsource.net/schemas/backup")] public enum ServicePlan { /// <remarks/> Essentials = 1, /// <remarks/> Advanced, /// <remarks/> Enterprise, } }```
a2f0fb97-630d-4772-b249-e4cb43ccbaa2
{ "language": "C#" }
```c# using Xunit; using System; using System.Collections; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Internal.Host; using System.Management.Automation.Runspaces; using Microsoft.PowerShell; using Microsoft.PowerShell.Linux.Host; namespace PSTests { public class SessionStateTests { [Fact] public void TestDrives() { PowerShellAssemblyLoadContextInitializer.SetPowerShellAssemblyLoadContext(AppContext.BaseDirectory); CultureInfo currentCulture = CultureInfo.CurrentCulture; PSHost hostInterface = new DefaultHost(currentCulture,currentCulture); RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); InitialSessionState iss = InitialSessionState.CreateDefault2(); AutomationEngine engine = new AutomationEngine(hostInterface, runspaceConfiguration, iss); ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss); SessionStateInternal sessionState = new SessionStateInternal(executionContext); Collection<PSDriveInfo> drives = sessionState.Drives(null); Assert.True(drives.Count>0); } } } ``` Add SessionStateTests to AssemblyLoadContext collection
```c# using Xunit; using System; using System.Collections; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Internal.Host; using System.Management.Automation.Runspaces; using Microsoft.PowerShell; using Microsoft.PowerShell.Linux.Host; namespace PSTests { [Collection("AssemblyLoadContext")] public class SessionStateTests { [Fact] public void TestDrives() { CultureInfo currentCulture = CultureInfo.CurrentCulture; PSHost hostInterface = new DefaultHost(currentCulture,currentCulture); RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); InitialSessionState iss = InitialSessionState.CreateDefault2(); AutomationEngine engine = new AutomationEngine(hostInterface, runspaceConfiguration, iss); ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss); SessionStateInternal sessionState = new SessionStateInternal(executionContext); Collection<PSDriveInfo> drives = sessionState.Drives(null); Assert.True(drives.Count>0); } } } ```
feb0bf19-9949-42ce-a9b0-0f8b0d7eb502
{ "language": "C#" }
```c# using System.Text; using log4net; using Mail2Bug.Email.EWS; namespace Mail2Bug.Email { class AckEmailHandler { private readonly Config.InstanceConfig _config; public AckEmailHandler(Config.InstanceConfig config) { _config = config; } /// <summary> /// Send mail announcing receipt of new ticket /// </summary> public void SendAckEmail(IIncomingEmailMessage originalMessage, string workItemId) { // Don't send ack emails if it's disabled in configuration or if we're in simulation mode if (!_config.EmailSettings.SendAckEmails || _config.TfsServerConfig.SimulationMode) { Logger.DebugFormat("Ack emails disabled in configuration - skipping"); return; } var ewsMessage = originalMessage as EWSIncomingMessage; if (ewsMessage != null) { HandleEWSMessage(ewsMessage, workItemId); } } private void HandleEWSMessage(EWSIncomingMessage originalMessage, string workItemId) { originalMessage.Reply(GetReplyContents(workItemId), _config.EmailSettings.AckEmailsRecipientsAll); } private string GetReplyContents(string workItemId) { var bodyBuilder = new StringBuilder(); bodyBuilder.Append(_config.EmailSettings.GetReplyTemplate()); bodyBuilder.Replace("[BUGID]", workItemId); bodyBuilder.Replace("[TFSCollectionUri]", _config.TfsServerConfig.CollectionUri); return bodyBuilder.ToString(); } private static readonly ILog Logger = LogManager.GetLogger(typeof(AckEmailHandler)); } } ``` Send Ack emails even if the system is in Simulation Mode.
```c# using System.Text; using log4net; using Mail2Bug.Email.EWS; namespace Mail2Bug.Email { class AckEmailHandler { private readonly Config.InstanceConfig _config; public AckEmailHandler(Config.InstanceConfig config) { _config = config; } /// <summary> /// Send mail announcing receipt of new ticket /// </summary> public void SendAckEmail(IIncomingEmailMessage originalMessage, string workItemId) { // Don't send ack emails if it's disabled in configuration if (!_config.EmailSettings.SendAckEmails) { Logger.DebugFormat("Ack emails disabled in configuration - skipping"); return; } var ewsMessage = originalMessage as EWSIncomingMessage; if (ewsMessage != null) { HandleEWSMessage(ewsMessage, workItemId); } } private void HandleEWSMessage(EWSIncomingMessage originalMessage, string workItemId) { originalMessage.Reply(GetReplyContents(workItemId), _config.EmailSettings.AckEmailsRecipientsAll); } private string GetReplyContents(string workItemId) { var bodyBuilder = new StringBuilder(); bodyBuilder.Append(_config.EmailSettings.GetReplyTemplate()); bodyBuilder.Replace("[BUGID]", workItemId); bodyBuilder.Replace("[TFSCollectionUri]", _config.TfsServerConfig.CollectionUri); return bodyBuilder.ToString(); } private static readonly ILog Logger = LogManager.GetLogger(typeof(AckEmailHandler)); } } ```
4334ee36-b469-478b-8ceb-60dd12c50c02
{ "language": "C#" }
```c# using System; using Model = Discord.API.InviteMetadata; namespace Discord.Rest { public class RestInviteMetadata : RestInvite, IInviteMetadata { private long _createdAtTicks; public bool IsRevoked { get; private set; } public bool IsTemporary { get; private set; } public int? MaxAge { get; private set; } public int? MaxUses { get; private set; } public int Uses { get; private set; } public RestUser Inviter { get; private set; } public DateTimeOffset CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks); internal RestInviteMetadata(BaseDiscordClient discord, IGuild guild, IChannel channel, string id) : base(discord, guild, channel, id) { } internal static RestInviteMetadata Create(BaseDiscordClient discord, IGuild guild, IChannel channel, Model model) { var entity = new RestInviteMetadata(discord, guild, channel, model.Code); entity.Update(model); return entity; } internal void Update(Model model) { base.Update(model); Inviter = RestUser.Create(Discord, model.Inviter); IsRevoked = model.Revoked; IsTemporary = model.Temporary; MaxAge = model.MaxAge != 0 ? model.MaxAge : (int?)null; MaxUses = model.MaxUses; Uses = model.Uses; _createdAtTicks = model.CreatedAt.UtcTicks; } IUser IInviteMetadata.Inviter => Inviter; } } ``` Add support for invites without attached users
```c# using System; using Model = Discord.API.InviteMetadata; namespace Discord.Rest { public class RestInviteMetadata : RestInvite, IInviteMetadata { private long _createdAtTicks; public bool IsRevoked { get; private set; } public bool IsTemporary { get; private set; } public int? MaxAge { get; private set; } public int? MaxUses { get; private set; } public int Uses { get; private set; } public RestUser Inviter { get; private set; } public DateTimeOffset CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks); internal RestInviteMetadata(BaseDiscordClient discord, IGuild guild, IChannel channel, string id) : base(discord, guild, channel, id) { } internal static RestInviteMetadata Create(BaseDiscordClient discord, IGuild guild, IChannel channel, Model model) { var entity = new RestInviteMetadata(discord, guild, channel, model.Code); entity.Update(model); return entity; } internal void Update(Model model) { base.Update(model); Inviter = model.Inviter != null ? RestUser.Create(Discord, model.Inviter) : null; IsRevoked = model.Revoked; IsTemporary = model.Temporary; MaxAge = model.MaxAge != 0 ? model.MaxAge : (int?)null; MaxUses = model.MaxUses; Uses = model.Uses; _createdAtTicks = model.CreatedAt.UtcTicks; } IUser IInviteMetadata.Inviter => Inviter; } } ```
d4ad60c1-d37c-4084-9ed1-f13a15a31492
{ "language": "C#" }
```c# using Newtonsoft.Json; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Webpack.AspNetCore.Internal; namespace Webpack.AspNetCore.Static { internal class PhysicalFileManifestReader : IManifestReader { private readonly WebpackContext context; public PhysicalFileManifestReader(WebpackContext context) { this.context = context ?? throw new System.ArgumentNullException(nameof(context)); } public async ValueTask<IDictionary<string, string>> ReadAsync() { var manifestFileInfo = context.GetManifestFileInfo(); if (!manifestFileInfo.Exists) { return null; } try { using (var manifestStream = manifestFileInfo.CreateReadStream()) { using (var manifestReader = new StreamReader(manifestStream)) { var manifestJson = await manifestReader.ReadToEndAsync(); try { return JsonConvert.DeserializeObject<Dictionary<string, string>>( manifestJson ); } catch (JsonException) { return null; } } } } catch (FileNotFoundException) { return null; } } } } ``` Update exception handling for physical file manifest reader
```c# using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Webpack.AspNetCore.Internal; namespace Webpack.AspNetCore.Static { internal class PhysicalFileManifestReader : IManifestReader { private readonly WebpackContext context; public PhysicalFileManifestReader(WebpackContext context) { this.context = context ?? throw new System.ArgumentNullException(nameof(context)); } /// <summary> /// Reads manifest from the physical file, specified in /// <see cref="WebpackContext" /> as a deserialized dictionary /// </summary> /// <returns> /// Manifest dictionary if succeeded to read and parse json manifest file, /// otherwise false /// </returns> public async ValueTask<IDictionary<string, string>> ReadAsync() { var manifestFileInfo = context.GetManifestFileInfo(); if (!manifestFileInfo.Exists) { return null; } try { // even though we've checked if the manifest // file exists by the time we get here the file // could become deleted or partially updated using (var manifestStream = manifestFileInfo.CreateReadStream()) using (var manifestReader = new StreamReader(manifestStream)) { var manifestJson = await manifestReader.ReadToEndAsync(); return JsonConvert.DeserializeObject<Dictionary<string, string>>( manifestJson ); } } catch (Exception ex) when (shouldHandle(ex)) { return null; } bool shouldHandle(Exception ex) => ex is IOException || ex is JsonException; } } } ```
cbfce50e-e858-4255-93c1-d84d1b0ea9cb
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class TableNetworking : NetworkBehaviour { [SyncVar] public string variant; [SyncVar] public string table; [SyncVar] public bool selected; [ServerCallback] void Start () { selected = false; table = ""; variant = ""; } public string GetTable() { return table; } public string GetVariant() { return variant; } public bool ServerHasSelected() { return selected; } public void SetTableInfo(string serverVariant, string serverTable) { selected = true; variant = serverVariant; table = serverTable; } } ``` Add debug log for latency on server
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class TableNetworking : NetworkBehaviour { [SyncVar] public string variant; [SyncVar] public string table; [SyncVar] public bool selected; public float logPingFrequency = 5.0f; [ServerCallback] void Start () { selected = false; table = ""; variant = ""; InvokeRepeating("LogPing", 0.0f, logPingFrequency); } void OnClientConnect(NetworkConnection conn) { InvokeRepeating("LogPing", 0.0f, logPingFrequency); } void LogPing() { foreach (NetworkClient conn in NetworkClient.allClients) { Debug.Log("Ping for connection " + conn.connection.address.ToString() + ": " + conn.GetRTT().ToString() + " (ms)"); } } public string GetTable() { return table; } public string GetVariant() { return variant; } public bool ServerHasSelected() { return selected; } public void SetTableInfo(string serverVariant, string serverTable) { selected = true; variant = serverVariant; table = serverTable; } } ```
198a2155-44b7-47cb-b0dd-87f053818fbd
{ "language": "C#" }
```c# using ServiceStack.ServiceHost; using Rainy.Db; using ServiceStack.OrmLite; using System; using ServiceStack.ServiceInterface.Cors; using ServiceStack.Common.Web; namespace Rainy.WebService.Admin { [Route("/api/admin/status/","GET, OPTIONS")] [AdminPasswordRequired] public class StatusRequest : IReturn<Status> { } public class StatusService : ServiceBase { public StatusService (IDbConnectionFactory fac) : base (fac) { } public Status Get (StatusRequest req) { var s = new Status (); s.Uptime = MainClass.Uptime; s.NumberOfRequests = MainClass.ServedRequests; // determine number of users using (var conn = connFactory.OpenDbConnection ()) { s.NumberOfUser = conn.Scalar<int>("SELECT COUNT(*) FROM DBUser"); s.TotalNumberOfNotes = conn.Scalar<int>("SELECT COUNT(*) FROM DBNote"); s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser; }; return s; } } public class Status { public DateTime Uptime { get; set; } public int NumberOfUser { get; set; } public long NumberOfRequests { get; set; } public int TotalNumberOfNotes { get; set; } public float AverageNotesPerUser { get; set; } } }``` Fix division by zero bug for status service
```c# using ServiceStack.ServiceHost; using Rainy.Db; using ServiceStack.OrmLite; using System; using ServiceStack.ServiceInterface.Cors; using ServiceStack.Common.Web; namespace Rainy.WebService.Admin { [Route("/api/admin/status/","GET, OPTIONS")] [AdminPasswordRequired] public class StatusRequest : IReturn<Status> { } public class StatusService : ServiceBase { public StatusService (IDbConnectionFactory fac) : base (fac) { } public Status Get (StatusRequest req) { var s = new Status (); s.Uptime = MainClass.Uptime; s.NumberOfRequests = MainClass.ServedRequests; // determine number of users using (var conn = connFactory.OpenDbConnection ()) { s.NumberOfUser = conn.Scalar<int>("SELECT COUNT(*) FROM DBUser"); s.TotalNumberOfNotes = conn.Scalar<int>("SELECT COUNT(*) FROM DBNote"); if (s.NumberOfUser > 0) s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser; }; return s; } } public class Status { public DateTime Uptime { get; set; } public int NumberOfUser { get; set; } public long NumberOfRequests { get; set; } public int TotalNumberOfNotes { get; set; } public float AverageNotesPerUser { get; set; } } }```
41930b13-f1a1-4db7-9628-31ac893c603d
{ "language": "C#" }
```c# #if NETFRAMEWORK using System; using Oracle.ManagedDataAccess.Client; public static class OracleConnectionBuilder { public static OracleConnection Build() { return Build(false); } public static OracleConnection Build(bool disableMetadataPooling) { var connection = Environment.GetEnvironmentVariable("OracleConnectionString"); if (string.IsNullOrWhiteSpace(connection)) { throw new Exception("OracleConnectionString environment variable is empty"); } if (disableMetadataPooling) { var builder = new OracleConnectionStringBuilder(connection) { MetadataPooling = false }; connection = builder.ConnectionString; } return new OracleConnection(connection); } } #endif``` Remove conditional Oracle connection builder compilation
```c# using System; using Oracle.ManagedDataAccess.Client; public static class OracleConnectionBuilder { public static OracleConnection Build() { return Build(false); } public static OracleConnection Build(bool disableMetadataPooling) { var connection = Environment.GetEnvironmentVariable("OracleConnectionString"); if (string.IsNullOrWhiteSpace(connection)) { throw new Exception("OracleConnectionString environment variable is empty"); } if (disableMetadataPooling) { var builder = new OracleConnectionStringBuilder(connection) { MetadataPooling = false }; connection = builder.ConnectionString; } return new OracleConnection(connection); } } ```
9aaa80db-6964-4db3-bf60-dd4c09f6c7dd
{ "language": "C#" }
```c#  #if NET45 using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.DependencyInjection; using Microsoft.AspNet.DependencyInjection.Fallback; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Routing; namespace MvcSample.Web { public class Startup { public void Configuration(IBuilder builder) { var services = new ServiceCollection(); services.Add(MvcServices.GetDefaultServices()); services.AddSingleton<PassThroughAttribute, PassThroughAttribute>(); var serviceProvider = services.BuildServiceProvider(builder.ServiceProvider); var routes = new RouteCollection() { DefaultHandler = new MvcApplication(serviceProvider), }; // TODO: Add support for route constraints, so we can potentially constrain by existing routes routes.MapRoute("{area}/{controller}/{action}"); routes.MapRoute( "{controller}/{action}", new { controller = "Home", action = "Index" }); routes.MapRoute( "{controller}", new { controller = "Home" }); builder.UseRouter(routes); } } } #endif ``` Remove ifdef for net45 in sample
```c# using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.DependencyInjection; using Microsoft.AspNet.DependencyInjection.Fallback; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Routing; namespace MvcSample.Web { public class Startup { public void Configuration(IBuilder builder) { var services = new ServiceCollection(); services.Add(MvcServices.GetDefaultServices()); services.AddSingleton<PassThroughAttribute, PassThroughAttribute>(); var serviceProvider = services.BuildServiceProvider(builder.ServiceProvider); var routes = new RouteCollection() { DefaultHandler = new MvcApplication(serviceProvider), }; // TODO: Add support for route constraints, so we can potentially constrain by existing routes routes.MapRoute("{area}/{controller}/{action}"); routes.MapRoute( "{controller}/{action}", new { controller = "Home", action = "Index" }); routes.MapRoute( "{controller}", new { controller = "Home" }); builder.UseRouter(routes); } } } ```
1868e6ef-3256-4730-b977-beec590b8dbb
{ "language": "C#" }
```c# using BatteryCommander.Web.Models.Data; using System; using Xunit; namespace BatteryCommander.Tests { public class ACFTTests { [Theory] [InlineData(15, 54, 84)] public void Calculate_Run_Score(int minutes, int seconds, int expected) { Assert.Equal(expected, ACFTScoreTables.TwoMileRun(new TimeSpan(0, minutes, seconds))); } } } ``` Add basic test for pushups and run
```c# using BatteryCommander.Web.Models.Data; using System; using Xunit; namespace BatteryCommander.Tests { public class ACFTTests { [Theory] [InlineData(15, 54, 84)] [InlineData(13, 29, 100)] [InlineData(23, 01, 0)] [InlineData(19, 05, 64)] [InlineData(17, 42, 72)] public void Calculate_Run_Score(int minutes, int seconds, int expected) { Assert.Equal(expected, ACFTScoreTables.TwoMileRun(new TimeSpan(0, minutes, seconds))); } [Theory] [InlineData(61, 100)] [InlineData(30, 70)] public void Calculate_Pushups(int reps, int expected) { Assert.Equal(expected, ACFTScoreTables.HandReleasePushUps(reps)); } } } ```
1f9bb29b-7827-42f9-a356-2db9513251c0
{ "language": "C#" }
```c# using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using FluentNHibernate.Mapping; using UCDArch.Core.DomainModel; namespace Commencement.Core.Domain { public class Template : DomainObject { public Template(string bodyText, TemplateType templateType, Ceremony ceremony) { BodyText = bodyText; TemplateType = templateType; Ceremony = ceremony; SetDefaults(); } public Template() { SetDefaults(); } private void SetDefaults() { IsActive = true; } [Required] public virtual string BodyText { get; set; } [Required] public virtual TemplateType TemplateType { get; set; } [Required] public virtual Ceremony Ceremony { get; set; } public virtual bool IsActive { get; set; } [StringLength(100)] public virtual string Subject { get; set; } } public class TemplateMap : ClassMap<Template> { public TemplateMap() { Id(x => x.Id); Map(x => x.BodyText); Map(x => x.IsActive); Map(x => x.Subject); References(x => x.TemplateType); References(x => x.Ceremony); } } } ``` Make sure BodyText can take a large string.
```c# using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using FluentNHibernate.Mapping; using UCDArch.Core.DomainModel; namespace Commencement.Core.Domain { public class Template : DomainObject { public Template(string bodyText, TemplateType templateType, Ceremony ceremony) { BodyText = bodyText; TemplateType = templateType; Ceremony = ceremony; SetDefaults(); } public Template() { SetDefaults(); } private void SetDefaults() { IsActive = true; } [Required] public virtual string BodyText { get; set; } [Required] public virtual TemplateType TemplateType { get; set; } [Required] public virtual Ceremony Ceremony { get; set; } public virtual bool IsActive { get; set; } [StringLength(100)] public virtual string Subject { get; set; } } public class TemplateMap : ClassMap<Template> { public TemplateMap() { Id(x => x.Id); Map(x => x.BodyText).Length(int.MaxValue); Map(x => x.IsActive); Map(x => x.Subject); References(x => x.TemplateType); References(x => x.Ceremony); } } } ```
71177b20-e3c2-486b-b22b-c6ab269b475e
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; namespace osu.Game.Tests.NonVisual { [TestFixture] public class BeatmapSetInfoEqualityTest { [Test] public void TestOnlineWithOnline() { var ourInfo = new BeatmapSetInfo { OnlineID = 123 }; var otherInfo = new BeatmapSetInfo { OnlineID = 123 }; Assert.AreEqual(ourInfo, otherInfo); } [Test] public void TestDatabasedWithDatabased() { var ourInfo = new BeatmapSetInfo { ID = 123 }; var otherInfo = new BeatmapSetInfo { ID = 123 }; Assert.AreEqual(ourInfo, otherInfo); } [Test] public void TestDatabasedWithOnline() { var ourInfo = new BeatmapSetInfo { ID = 123, OnlineID = 12 }; var otherInfo = new BeatmapSetInfo { OnlineID = 12 }; Assert.AreEqual(ourInfo, otherInfo); } [Test] public void TestCheckNullID() { var ourInfo = new BeatmapSetInfo { Hash = "1" }; var otherInfo = new BeatmapSetInfo { Hash = "2" }; Assert.AreNotEqual(ourInfo, otherInfo); } } } ``` Update tests to match new equality not including online ID checks
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Extensions; namespace osu.Game.Tests.NonVisual { [TestFixture] public class BeatmapSetInfoEqualityTest { [Test] public void TestOnlineWithOnline() { var ourInfo = new BeatmapSetInfo { OnlineID = 123 }; var otherInfo = new BeatmapSetInfo { OnlineID = 123 }; Assert.AreNotEqual(ourInfo, otherInfo); Assert.IsTrue(ourInfo.MatchesOnlineID(otherInfo)); } [Test] public void TestDatabasedWithDatabased() { var ourInfo = new BeatmapSetInfo { ID = 123 }; var otherInfo = new BeatmapSetInfo { ID = 123 }; Assert.AreEqual(ourInfo, otherInfo); } [Test] public void TestDatabasedWithOnline() { var ourInfo = new BeatmapSetInfo { ID = 123, OnlineID = 12 }; var otherInfo = new BeatmapSetInfo { OnlineID = 12 }; Assert.AreNotEqual(ourInfo, otherInfo); Assert.IsTrue(ourInfo.MatchesOnlineID(otherInfo)); } [Test] public void TestCheckNullID() { var ourInfo = new BeatmapSetInfo { Hash = "1" }; var otherInfo = new BeatmapSetInfo { Hash = "2" }; Assert.AreNotEqual(ourInfo, otherInfo); } } } ```
1c1dc22e-8b4f-429b-a500-4532d1fd496f
{ "language": "C#" }
```c# using System.IO; using System.Runtime.CompilerServices; using Assent; namespace ExpressionToCodeTest { static class ApprovalTest { public static void Verify(string text, [CallerFilePath] string filepath = null, [CallerMemberName] string membername = null) { var filename = Path.GetFileNameWithoutExtension(filepath); var filedir = Path.GetDirectoryName(filepath); var config = new Configuration().UsingNamer(new Assent.Namers.FixedNamer(Path.Combine(filedir, filename + "." + membername))); "bla".Assent(text, config, membername, filepath); //var writer = WriterFactory.CreateTextWriter(text); //var namer = new SaneNamer { Name = filename + "." + membername, SourcePath = filedir }; //var reporter = new DiffReporter(); //Approver.Verify(new FileApprover(writer, namer, true), reporter); } //public class SaneNamer : IApprovalNamer //{ // public string SourcePath { get; set; } // public string Name { get; set; } //} } } ``` Throw exception for crazy input
```c# using System.IO; using System.Runtime.CompilerServices; using Assent; namespace ExpressionToCodeTest { static class ApprovalTest { public static void Verify(string text, [CallerFilePath] string filepath = null, [CallerMemberName] string membername = null) { var filename = Path.GetFileNameWithoutExtension(filepath); var filedir = Path.GetDirectoryName(filepath) ?? throw new InvalidOperationException("path " + filepath + " has no directory"); var config = new Configuration().UsingNamer(new Assent.Namers.FixedNamer(Path.Combine(filedir, filename + "." + membername))); "bla".Assent(text, config, membername, filepath); //var writer = WriterFactory.CreateTextWriter(text); //var namer = new SaneNamer { Name = filename + "." + membername, SourcePath = filedir }; //var reporter = new DiffReporter(); //Approver.Verify(new FileApprover(writer, namer, true), reporter); } //public class SaneNamer : IApprovalNamer //{ // public string SourcePath { get; set; } // public string Name { get; set; } //} } } ```
7d34a09b-bea9-4be2-a106-0b516b63ebe9
{ "language": "C#" }
```c# using System; using System.Linq; using NUnit.Framework; namespace Faker.Tests { [TestFixture] public class RandomNumberFixture { [TestCase(1, "Coin flip")] // 0 ... 1 Coin flip [TestCase(6, "6 sided die")] // 0 .. 6 [TestCase(9, "Random single digit")] // 0 ... 9 [TestCase(20, "D20")] // 0 ... 20 The signature dice of the dungeons and dragons public void Should_Yield_All_ValuesWithinRange(int maxValue, string testName) { var maxExclusiveLimit = maxValue + 1; Console.WriteLine($@"RandomNumber.Next [{testName}]"); var results = Enumerable.Range(0, maxExclusiveLimit).ToDictionary(k => k, k => false); do { var randValue = RandomNumber.Next(0, maxExclusiveLimit); results[randValue] = true; Console.WriteLine($@"RandomNumber.Next(0,maxValueExclusive)=[{randValue}]"); } while (!results.All(j => j.Value)); Assert.IsTrue(results.Select(z => z.Value).All(y => y)); } [Test] public void Should_Create_Zero() { var zero = RandomNumber.Next(0, 0); Console.WriteLine($@"RandomNumber.Next(0,0)=[{zero}]"); Assert.IsTrue(zero == 0); } } }``` Fix name on test console write out
```c# using System; using System.Linq; using NUnit.Framework; namespace Faker.Tests { [TestFixture] public class RandomNumberFixture { [TestCase(1, "Coin flip")] // 0 ... 1 Coin flip [TestCase(6, "6 sided die")] // 0 .. 6 [TestCase(9, "Random single digit")] // 0 ... 9 [TestCase(20, "D20")] // 0 ... 20 The signature dice of the dungeons and dragons public void Should_Yield_All_ValuesWithinRange(int maxValue, string testName) { var maxExclusiveLimit = maxValue + 1; Console.WriteLine($@"RandomNumber.Next [{testName}]"); var results = Enumerable.Range(0, maxExclusiveLimit).ToDictionary(k => k, k => false); do { var randValue = RandomNumber.Next(0, maxExclusiveLimit); results[randValue] = true; Console.WriteLine($@"RandomNumber.Next(0,{maxExclusiveLimit})=[{randValue}]"); } while (!results.All(j => j.Value)); Assert.IsTrue(results.Select(z => z.Value).All(y => y)); } [Test] public void Should_Create_Zero() { var zero = RandomNumber.Next(0, 0); Console.WriteLine($@"RandomNumber.Next(0,0)=[{zero}]"); Assert.IsTrue(zero == 0); } } }```
537e9251-de46-4fb2-9f3f-dacdf8c9e5f5
{ "language": "C#" }
```c# using System; namespace Rooijakkers.MeditationTimer.Data { /// <summary> /// Stores settings data in local settings storage /// </summary> public class Settings { private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage"; public TimeSpan TimeToGetReady { get { var secondsToGetReady = Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE]; if (secondsToGetReady == null) { secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS; SetTimeToGetReady(Convert.ToInt32(secondsToGetReady)); } // Return stored time in seconds as a TimeSpan. return new TimeSpan(0, 0, Convert.ToInt32(secondsToGetReady)); } set { // Store time in seconds obtained from TimeSpan. SetTimeToGetReady(value.Seconds); } } private void SetTimeToGetReady(int value) { Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value; } } } ``` Make settings object bit cleaner
```c# using System; namespace Rooijakkers.MeditationTimer.Data { /// <summary> /// Stores settings data in local settings storage /// </summary> public class Settings { private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage"; public TimeSpan TimeToGetReady { get { int? secondsToGetReady = Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] as int?; // If settings were not yet stored set to default value. if (secondsToGetReady == null) { secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS; SetTimeToGetReady(secondsToGetReady.Value); } // Return stored time in seconds as a TimeSpan. return new TimeSpan(0, 0, secondsToGetReady.Value); } set { // Store time in seconds obtained from TimeSpan. SetTimeToGetReady(value.Seconds); } } private void SetTimeToGetReady(int value) { Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value; } } } ```
c321a1a0-1f87-4260-83b4-cc705dfc5465
{ "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 enable using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using osu.Game.Online.API; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings> { public int? BeatmapID { get; set; } public int? RulesetID { get; set; } [NotNull] public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>(); public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID; public override string ToString() => $"Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}"; } } ``` Add room name to settings
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using osu.Game.Online.API; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings> { public int? BeatmapID { get; set; } public int? RulesetID { get; set; } public string Name { get; set; } = "Unnamed room"; [NotNull] public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>(); public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal); public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}"; } } ```
7305c439-2bd3-4512-b58f-99ab9336b3eb
{ "language": "C#" }
```c# <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Calendar Proxy</title> <link href="~/Content/iCalStyles.min.css" rel="stylesheet" /> <link href="~/Content/timer.min.css" rel="stylesheet" /> <link href="~/Content/calendar-proxy-form.css" rel="stylesheet" /> <link href="~/Content/texteffects.min.css" rel="stylesheet" /> </head> <body> <div class="navbar fixed-top navbar-dark bg-primary"> <div class="container"> <div class="navbar-header"> @Html.ActionLink("Calendar Proxy", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> </div> </div> <div class="body-content"> <div class="container"> @RenderBody() </div> </div> <script src="~/Scripts/ical.min.js"></script> <script src="~/Scripts/jquery-3.4.1.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <script src="~/Scripts/icalrender.min.js"></script> <script src="~/Scripts/calendar-proxy-form.min.js"></script> </body> </html>``` Add missing bootstrap reference (after removing bootswatch)
```c# <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Calendar Proxy</title> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/iCalStyles.min.css" rel="stylesheet" /> <link href="~/Content/timer.min.css" rel="stylesheet" /> <link href="~/Content/calendar-proxy-form.css" rel="stylesheet" /> <link href="~/Content/texteffects.min.css" rel="stylesheet" /> </head> <body> <div class="navbar fixed-top navbar-dark bg-primary"> <div class="container"> <div class="navbar-header"> @Html.ActionLink("Calendar Proxy", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> </div> </div> <div class="body-content"> <div class="container"> @RenderBody() </div> </div> <script src="~/Scripts/ical.min.js"></script> <script src="~/Scripts/jquery-3.4.1.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <script src="~/Scripts/icalrender.min.js"></script> <script src="~/Scripts/calendar-proxy-form.min.js"></script> </body> </html>```
61dee76e-2722-4968-8c4b-32d146cd26b9
{ "language": "C#" }
```c# namespace OmniSharp.Rename { public class ModifiedFileResponse { public ModifiedFileResponse() {} public ModifiedFileResponse(string fileName, string buffer) { this.FileName = fileName; this.Buffer = buffer; } public string FileName { get; set; } public string Buffer { get; set; } } } ``` Add Cygwin path replacement for Rename/Override
```c# using OmniSharp.Solution; namespace OmniSharp.Rename { public class ModifiedFileResponse { private string _fileName; public ModifiedFileResponse() {} public ModifiedFileResponse(string fileName, string buffer) { this.FileName = fileName; this.Buffer = buffer; } public string FileName { get { return _fileName; } set { _fileName = value.ApplyPathReplacementsForClient(); } } public string Buffer { get; set; } } } ```
72f5023c-9d58-4840-bf3b-3ff4f24511f8
{ "language": "C#" }
```c# namespace Gu.Units.Tests { using NUnit.Framework; public class UnitParserTests { [TestCase("1m", 1)] [TestCase("-1m", -1)] [TestCase("1e3m", 1e3)] [TestCase("1e+3m", 1e+3)] [TestCase("-1e+3m", -1e+3)] [TestCase("1e-3m", 1e-3)] [TestCase("-1e-3m", -1e-3)] [TestCase(" 1m", 1)] [TestCase("1m ", 1)] [TestCase("1 m", 1)] [TestCase("1 m ", 1)] [TestCase("1 m", 1)] [TestCase("1m ", 1)] public void ParseLength(string s, double expected) { var length = UnitParser.Parse<ILengthUnit, Length>(s, Length.From); Assert.AreEqual(expected, length.Meters); } [TestCase("1s", 1)] public void ParseTime(string s, double expected) { var time = UnitParser.Parse<ITimeUnit, Time>(s, Time.From); Assert.AreEqual(expected, time.Seconds); } } } ``` Revert "Added 5 tests for Length and a test for Time"
```c# namespace Gu.Units.Tests { using NUnit.Framework; public class UnitParserTests { [TestCase("1m", 1)] [TestCase("-1m", 1)] [TestCase("1e3m", 1e3)] [TestCase("1e+3m", 1e+3)] [TestCase("1e-3m", 1e-3)] [TestCase(" 1m", 1)] [TestCase("1 m", 1)] [TestCase("1m ", 1)] public void ParseLength(string s, double expected) { var length = UnitParser.Parse<ILengthUnit, Length>(s, Length.From); Assert.AreEqual(expected, length.Meters); } } } ```
f90ff336-c4fd-47d8-a5d7-74167d6fe1fe
{ "language": "C#" }
```c# using System.Reflection; #if XAMMAC [assembly: AssemblyTitle("Eto.Forms - OS X Platform using Xamarin.Mac")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")] #else [assembly: AssemblyTitle("Eto.Forms - OS X Platform using MonoMac")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")] #endif ``` Use better title for Mac/Mac64/XamMac assemblies/nuget packages
```c# using System.Reflection; #if XAMMAC [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")] #elif Mac64 [assembly: AssemblyTitle("Eto.Forms - MonoMac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")] #else [assembly: AssemblyTitle("Eto.Forms - MonoMac 64-bit Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac with 64-bit mono")] #endif ```
f58b19fa-b36a-4500-b0da-b00992f494c8
{ "language": "C#" }
```c# @using Microsoft.AspNetCore.Identity @using mvc_individual_authentication.Models @inject SignInManager<ApplicationUser> SignInManager @inject UserManager<ApplicationUser> UserManager @if (SignInManager.IsSignedIn(User)) { <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right"> <ul class="nav navbar-nav navbar-right"> <li> <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a> </li> <li> <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button> </li> </ul> </form> } else { <ul class="nav navbar-nav navbar-right"> <li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li> <li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li> </ul> } ``` Rework login partial to BS4
```c# @using Microsoft.AspNetCore.Identity @using mvc_individual_authentication.Models @inject SignInManager<ApplicationUser> SignInManager @inject UserManager<ApplicationUser> UserManager @if (SignInManager.IsSignedIn(User)) { <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" class="form-inline"> <ul class="navbar-nav"> <li> <a class="btn btn-link nav-link" asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a> </li> <li> <button type="submit" class="btn btn-link nav-link">Log out</button> </li> </ul> </form> } else { <ul class="navbar-nav"> <li><a class="nav-link" asp-area="" asp-controller="Account" asp-action="Register">Register</a></li> <li><a class="nav-link" asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li> </ul> } ```
31478ddf-9e4b-4139-8b2f-f2eecbae5258
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. using System; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft.DirectX")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("alesliehughes")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] ``` Set specific version for Microsoft.DirectX.dll.
```c# using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. using System; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft.DirectX")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("alesliehughes")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.2902.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] ```
9055314f-b33c-4395-819d-8eb861505a0c
{ "language": "C#" }
```c# // Copyright 2013 J.C. Moyer // // 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. #pragma warning disable 649 using System; using Newtonsoft.Json; namespace Yeena.PathOfExile { [JsonObject] class PoEItemSocket { [JsonProperty("group")] private readonly int _group; [JsonProperty("attr")] private readonly string _attr; public int Group { get { return _group; } } public PoESocketColor Color { get { return PoESocketColorUtilities.Parse(_attr); } } public override string ToString() { return Enum.GetName(typeof(PoESocketColor), Color); } } } ``` Use ToString instead of Enum.GetName
```c# // Copyright 2013 J.C. Moyer // // 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. #pragma warning disable 649 using Newtonsoft.Json; namespace Yeena.PathOfExile { [JsonObject] class PoEItemSocket { [JsonProperty("group")] private readonly int _group; [JsonProperty("attr")] private readonly string _attr; public int Group { get { return _group; } } public PoESocketColor Color { get { return PoESocketColorUtilities.Parse(_attr); } } public override string ToString() { return Color.ToString(); } } } ```
415ace16-71fe-4093-b256-e0ebc096ec6d
{ "language": "C#" }
```c# using System; Console.WriteLine("Hello World!"); ``` Add a bunch of junk you might find in a top-level program
```c# using System; using System.Linq.Expressions; using ExpressionToCodeLib; const int SomeConst = 27; var myVariable = "implicitly closed over"; var withImplicitType = new { A = "ImplicitTypeMember", }; Console.WriteLine(ExpressionToCode.ToCode(() => myVariable)); new InnerClass().DoIt(); LocalFunction(123); void LocalFunction(int arg) { var inLocalFunction = 42; Expression<Func<int>> expression1 = () => inLocalFunction + myVariable.Length - arg - withImplicitType.A.Length * SomeConst; Console.WriteLine(ExpressionToCode.ToCode(expression1)); } sealed class InnerClass { public static int StaticInt = 37; public int InstanceInt = 12; public void DoIt() => Console.WriteLine(ExpressionToCode.ToCode(() => StaticInt + InstanceInt)); } ```
ae1c2e0c-71d8-4076-8347-f847444c9d6b
{ "language": "C#" }
```c# using System.Threading.Tasks; using Moq; using NUnit.Framework; using Ploeh.AutoFixture.NUnit3; using SlackConnector.Connections; using SlackConnector.Connections.Clients.Channel; using SlackConnector.Connections.Models; using SlackConnector.Connections.Sockets; using SlackConnector.Connections.Sockets.Messages.Outbound; using SlackConnector.Models; namespace SlackConnector.Tests.Unit.SlackConnectionTests { internal class PingTests { [Test, AutoMoqData] public async Task should_return_expected_slack_hub([Frozen]Mock<IConnectionFactory> connectionFactory, Mock<IChannelClient> channelClient, Mock<IWebSocketClient> webSocket, SlackConnection slackConnection) { // given const string slackKey = "key-yay"; const string userId = "some-id"; var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey }; await slackConnection.Initialise(connectionInfo); connectionFactory .Setup(x => x.CreateChannelClient()) .Returns(channelClient.Object); var returnChannel = new Channel { Id = "super-id", Name = "dm-channel" }; channelClient .Setup(x => x.JoinDirectMessageChannel(slackKey, userId)) .ReturnsAsync(returnChannel); // when await slackConnection.Ping(); // then webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>())); } } }``` Remove unused depedency from test
```c# using System.Threading.Tasks; using Moq; using NUnit.Framework; using Ploeh.AutoFixture.NUnit3; using SlackConnector.Connections; using SlackConnector.Connections.Sockets; using SlackConnector.Connections.Sockets.Messages.Outbound; using SlackConnector.Models; namespace SlackConnector.Tests.Unit.SlackConnectionTests { internal class PingTests { [Test, AutoMoqData] public async Task should_send_ping([Frozen]Mock<IConnectionFactory> connectionFactory, Mock<IWebSocketClient> webSocket, SlackConnection slackConnection) { // given const string slackKey = "key-yay"; var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey }; await slackConnection.Initialise(connectionInfo); // when await slackConnection.Ping(); // then webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>())); } } }```
1544fb32-ce2f-4582-a5a8-ba2fa5af83e9
{ "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 { TEntity GetKey(TPk key, ISession session); Task<TEntity> GetKeyAsync(TPk key, ISession session ); TEntity Get(TEntity entity, ISession session); Task<TEntity> GetAsync(TEntity entity, ISession session); IEnumerable<TEntity> GetAll(ISession session); Task<IEnumerable<TEntity>> GetAllAsync(ISession session); TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow); Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow); } }``` Expand interface to be more testable. So methods must have a session (i.e. not null) and add a generic for session when no session is needed.
```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 { TEntity GetKey(TPk key, ISession session); TEntity GetKey<TSesssion>(TPk key) where TSesssion : class, ISession; Task<TEntity> GetKeyAsync(TPk key, ISession session); Task<TEntity> GetKeyAsync<TSesssion>(TPk key) where TSesssion : class, ISession; TEntity Get(TEntity entity, ISession session); TEntity Get<TSesssion>(TEntity entity) where TSesssion : class, ISession; Task<TEntity> GetAsync(TEntity entity, ISession session); Task<TEntity> GetAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession; IEnumerable<TEntity> GetAll(ISession session); IEnumerable<TEntity> GetAll<TSesssion>() where TSesssion : class, ISession; Task<IEnumerable<TEntity>> GetAllAsync(ISession session); Task<IEnumerable<TEntity>> GetAllAsync<TSesssion>() where TSesssion : class, ISession; TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow); TPk SaveOrUpdate<TSesssion>(TEntity entity) where TSesssion : class, ISession; Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow); Task<TPk> SaveOrUpdateAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession; } }```
9253dd5c-7dda-46ca-87a3-f4e1b1d85f2a
{ "language": "C#" }
```c# namespace Glimpse.Core.Plugin.Assist { public static class FormattingKeywords { public const string Error = "error"; public const string Fail = "fail"; public const string Info = "info"; public const string Loading = "loading"; public const string Ms = "ms"; public const string Quiet = "quiet"; public const string Selected = "selected"; public const string Warn = "warn"; } }``` Convert FormattingKeyword enum to it class name counterparts
```c# namespace Glimpse.Core.Plugin.Assist { public static class FormattingKeywords { public const string Error = "error"; public const string Fail = "fail"; public const string Info = "info"; public const string Loading = "loading"; public const string Ms = "ms"; public const string Quiet = "quiet"; public const string Selected = "selected"; public const string Warn = "warn"; public static string Convert(FormattingKeywordEnum keyword) { switch (keyword) { case FormattingKeywordEnum.Error: return Error; case FormattingKeywordEnum.Fail: return Fail; case FormattingKeywordEnum.Info: return Info; case FormattingKeywordEnum.Loading: return Loading; case FormattingKeywordEnum.Quite: return Quiet; case FormattingKeywordEnum.Selected: return Selected; case FormattingKeywordEnum.System: return Ms; case FormattingKeywordEnum.Warn: return Warn; default: return null; } } } }```
e397dd34-b817-49e5-8b9e-b802348c8a75
{ "language": "C#" }
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace Auth0.AuthenticationApi { internal class OpenIdConfigurationCache { private static volatile OpenIdConfigurationCache _instance; private static readonly object SyncRoot = new object(); private readonly ConcurrentDictionary<string, OpenIdConnectConfiguration> _innerCache = new ConcurrentDictionary<string, OpenIdConnectConfiguration>(); private OpenIdConfigurationCache() {} public static OpenIdConfigurationCache Instance { get { if (_instance == null) { lock (SyncRoot) { if (_instance == null) _instance = new OpenIdConfigurationCache(); } } return _instance; } } public async Task<OpenIdConnectConfiguration> GetAsync(string domain) { _innerCache.TryGetValue(domain, out var configuration); if (configuration == null) { var uri = new Uri(domain); IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{uri.AbsoluteUri}.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); configuration = await configurationManager.GetConfigurationAsync(CancellationToken.None); _innerCache[domain] = configuration; } return configuration; } } }``` Load OIDC configuration from root of Authority
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace Auth0.AuthenticationApi { internal class OpenIdConfigurationCache { private static volatile OpenIdConfigurationCache _instance; private static readonly object SyncRoot = new object(); private readonly ConcurrentDictionary<string, OpenIdConnectConfiguration> _innerCache = new ConcurrentDictionary<string, OpenIdConnectConfiguration>(); private OpenIdConfigurationCache() {} public static OpenIdConfigurationCache Instance { get { if (_instance == null) { lock (SyncRoot) { if (_instance == null) _instance = new OpenIdConfigurationCache(); } } return _instance; } } public async Task<OpenIdConnectConfiguration> GetAsync(string domain) { _innerCache.TryGetValue(domain, out var configuration); if (configuration == null) { var uri = new Uri(domain); IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>( $"{uri.Scheme}://{uri.Authority}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); configuration = await configurationManager.GetConfigurationAsync(CancellationToken.None); _innerCache[domain] = configuration; } return configuration; } } }```
b8f24033-8e89-45dd-8d81-0685563a192c
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Screens; using osu.Game.Screens; using osu.Game.Screens.Menu; using osuTK.Graphics; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseOsuGame : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), }; public TestCaseOsuGame() { Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, new ScreenStack(new Loader()) { RelativeSizeAxes = Axes.Both, } }; } } } ``` Fix OsuGame test case not working
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Platform; using osu.Game.Screens.Menu; using osuTK.Graphics; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseOsuGame : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), }; [BackgroundDependencyLoader] private void load(GameHost host) { OsuGame game = new OsuGame(); game.SetHost(host); Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, game }; } } } ```
512356a8-284f-4de9-a721-03e58ba571f2
{ "language": "C#" }
```c# using System.Collections; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Utils { public class StaticCoroutine : MonoBehaviour { private static StaticCoroutine _mInstance; private static StaticCoroutine Instance { get { if (_mInstance != null) return _mInstance; _mInstance = FindObjectOfType(typeof(StaticCoroutine)) as StaticCoroutine ?? new GameObject("StaticCoroutineManager").AddComponent<StaticCoroutine>(); return _mInstance; } } [UsedImplicitly] void Awake() { if (_mInstance == null) { _mInstance = this; } } IEnumerator Perform(IEnumerator coroutine) { yield return StartCoroutine(coroutine); Die(); } /// <summary> /// Place your lovely static IEnumerator in here and witness magic! /// </summary> /// <param name="coroutine">Static IEnumerator</param> public static void DoCoroutine(IEnumerator coroutine) { Instance.StartCoroutine(Instance.Perform(coroutine)); //this will launch the coroutine on our instance } public static void Die() { Destroy(_mInstance.gameObject); _mInstance = null; } [UsedImplicitly] void OnApplicationQuit() { _mInstance = null; } } }``` Stop all coroutines on Die()
```c# using System.Collections; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Utils { public class StaticCoroutine : MonoBehaviour { private static StaticCoroutine _mInstance; private static StaticCoroutine Instance { get { if (_mInstance != null) return _mInstance; _mInstance = FindObjectOfType(typeof(StaticCoroutine)) as StaticCoroutine ?? new GameObject("StaticCoroutineManager").AddComponent<StaticCoroutine>(); return _mInstance; } } [UsedImplicitly] void Awake() { if (_mInstance == null) { _mInstance = this; } } IEnumerator Perform(IEnumerator coroutine) { yield return StartCoroutine(coroutine); Die(); } /// <summary> /// Place your lovely static IEnumerator in here and witness magic! /// </summary> /// <param name="coroutine">Static IEnumerator</param> public static void DoCoroutine(IEnumerator coroutine) { Instance.StartCoroutine(Instance.Perform(coroutine)); //this will launch the coroutine on our instance } public static void Die() { _mInstance.StopAllCoroutines(); Destroy(_mInstance.gameObject); _mInstance = null; } [UsedImplicitly] void OnApplicationQuit() { _mInstance = null; } } }```
a78fe0ab-7083-43ff-8434-a4ea78acf807
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; namespace System.Reflection.Metadata { public static class AssemblyExtensions { [DllImport(JitHelpers.QCall)] [SecurityCritical] // unsafe method [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length); // Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader. // - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET // native images, etc. // - Callers should not write to the metadata blob // - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is // associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the // metadata blob. [CLSCompliant(false)] // out byte* blob [SecurityCritical] // unsafe method public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length) { if (assembly == null) { throw new ArgumentNullException("assembly"); } blob = null; length = 0; return InternalTryGetRawMetadata((RuntimeAssembly)assembly, ref blob, ref length); } } } ``` Fix TryGetRawMetadata to return false when the assembly is not a RuntimeAssembly
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; namespace System.Reflection.Metadata { public static class AssemblyExtensions { [DllImport(JitHelpers.QCall)] [SecurityCritical] // unsafe method [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length); // Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader. // - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET // native images, etc. // - Callers should not write to the metadata blob // - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is // associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the // metadata blob. [CLSCompliant(false)] // out byte* blob [SecurityCritical] // unsafe method public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length) { if (assembly == null) { throw new ArgumentNullException("assembly"); } blob = null; length = 0; var runtimeAssembly = assembly as RuntimeAssembly; if (runtimeAssembly == null) { return false; } return InternalTryGetRawMetadata(runtimeAssembly, ref blob, ref length); } } } ```
c627020f-2ee6-4818-8b21-a501145b864c
{ "language": "C#" }
```c# using System; using Xunit; namespace FromString.Tests { public class ParsedTTests { [Fact] public void CanParseAnInt() { var parsedInt = new Parsed<int>("123"); Assert.True(parsedInt.HasValue); Assert.Equal(123, parsedInt.Value); } [Fact] public void AnInvalidStringSetsHasValueFalse() { var parsedInt = new Parsed<int>("this is not a string"); Assert.False(parsedInt.HasValue); } [Fact] public void AnInvalidStringThrowsExceptionWhenAccessingValue() { var parsedInt = new Parsed<int>("this is not a string"); Assert.Throws<InvalidOperationException>(() => parsedInt.Value); } [Fact] public void CanGetBackRawValue() { var parsedInt = new Parsed<int>("this is not a string"); Assert.Equal("this is not a string", parsedInt.RawValue); } [Fact] public void CanAssignValueDirectly() { Parsed<decimal> directDecimal = 123.45m; Assert.True(directDecimal.HasValue); Assert.Equal(123.45m, directDecimal.Value); } [Fact] public void ParsingInvalidUriFails() { var parsedUri = new Parsed<Uri>("this is not an URI"); Assert.False(parsedUri.HasValue); } } } ``` Test parsing valid absolute URI
```c# using System; using Xunit; namespace FromString.Tests { public class ParsedTTests { [Fact] public void CanParseAnInt() { var parsedInt = new Parsed<int>("123"); Assert.True(parsedInt.HasValue); Assert.Equal(123, parsedInt.Value); } [Fact] public void AnInvalidStringSetsHasValueFalse() { var parsedInt = new Parsed<int>("this is not a string"); Assert.False(parsedInt.HasValue); } [Fact] public void AnInvalidStringThrowsExceptionWhenAccessingValue() { var parsedInt = new Parsed<int>("this is not a string"); Assert.Throws<InvalidOperationException>(() => parsedInt.Value); } [Fact] public void CanGetBackRawValue() { var parsedInt = new Parsed<int>("this is not a string"); Assert.Equal("this is not a string", parsedInt.RawValue); } [Fact] public void CanAssignValueDirectly() { Parsed<decimal> directDecimal = 123.45m; Assert.True(directDecimal.HasValue); Assert.Equal(123.45m, directDecimal.Value); } [Fact] public void ParsingInvalidUriFails() { var parsedUri = new Parsed<Uri>("this is not an URI"); Assert.False(parsedUri.HasValue); } [Fact] public void ParsingValidAbsoluteUriSucceeds() { var parsedUri = new Parsed<Uri>("https://github.com/"); Assert.True(parsedUri.HasValue); Assert.Equal(new Uri("https://github.com/"), parsedUri.Value); } } } ```
9a355652-8ddc-4691-a751-234cf8bc5685
{ "language": "C#" }
```c# using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Running; using SwissArmyKnife.Benchmarks.Benches.Extensions; using System; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Toolchains.CsProj; namespace SwissArmyKnife.Benchmarks { class Program { private static void Main(string[] args) { var config = GetConfig(); var benchmarks = GetBenchmarks(); for (var i = 0; i < benchmarks.Length; i++) { var typeToRun = benchmarks[i]; BenchmarkRunner.Run(typeToRun, config); } //BenchmarkRunner.Run<StringExtensionsBenchmarks>(config); } private static Type[] GetBenchmarks() { var result = new Type[] { // Extensions typeof(ObjectExtensionsBenchmarks), typeof(IComparableExtensionsBenchmarks), typeof(StringBuilderExtensionsBenchmarks), typeof(StringExtensionsBenchmarks), typeof(IntExtensionsBenchmarks), }; return result; } private static IConfig GetConfig() { var config = ManualConfig.Create(DefaultConfig.Instance); config .AddDiagnoser(MemoryDiagnoser.Default); config.AddJob( Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31).AsBaseline(), Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp21), Job.Default.WithToolchain(CsProjClassicNetToolchain.Net48) ); return config; } } } ``` Remove running benchmarks on .NET Core 2.1
```c# using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Running; using SwissArmyKnife.Benchmarks.Benches.Extensions; using System; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Toolchains.CsProj; namespace SwissArmyKnife.Benchmarks { class Program { private static void Main(string[] args) { var config = GetConfig(); var benchmarks = GetBenchmarks(); for (var i = 0; i < benchmarks.Length; i++) { var typeToRun = benchmarks[i]; BenchmarkRunner.Run(typeToRun, config); } //BenchmarkRunner.Run<StringExtensionsBenchmarks>(config); } private static Type[] GetBenchmarks() { var result = new Type[] { // Extensions typeof(ObjectExtensionsBenchmarks), typeof(IComparableExtensionsBenchmarks), typeof(StringBuilderExtensionsBenchmarks), typeof(StringExtensionsBenchmarks), typeof(IntExtensionsBenchmarks), }; return result; } private static IConfig GetConfig() { var config = ManualConfig.Create(DefaultConfig.Instance); config .AddDiagnoser(MemoryDiagnoser.Default); config.AddJob( Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31).AsBaseline(), Job.Default.WithToolchain(CsProjClassicNetToolchain.Net48) ); return config; } } } ```
c0754fce-55cd-4256-acf8-fdf8622310b6
{ "language": "C#" }
```c# using System; using BudgetAnalyser.Engine.Annotations; namespace BudgetAnalyser.Engine.Widgets { public sealed class BudgetBucketMonitorWidget : RemainingBudgetBucketWidget, IUserDefinedWidget { private readonly string disabledToolTip; private string doNotUseId; public BudgetBucketMonitorWidget() { this.disabledToolTip = "Either a Statement, Budget, or a Filter are not present, or the Bucket Code is not valid, remaining budget cannot be calculated."; } public string Id { get { return this.doNotUseId; } set { this.doNotUseId = value; OnPropertyChanged(); BucketCode = Id; } } public Type WidgetType => GetType(); public void Initialise(MultiInstanceWidgetState state, ILogger logger) { } public override void Update([NotNull] params object[] input) { base.Update(input); if (!Enabled) { ToolTip = this.disabledToolTip; } } } }``` Fix labels not appearing on BucketMonitorWidget
```c# using System; using BudgetAnalyser.Engine.Annotations; namespace BudgetAnalyser.Engine.Widgets { public sealed class BudgetBucketMonitorWidget : RemainingBudgetBucketWidget, IUserDefinedWidget { private readonly string disabledToolTip; private string doNotUseId; public BudgetBucketMonitorWidget() { this.disabledToolTip = "Either a Statement, Budget, or a Filter are not present, or the Bucket Code is not valid, remaining budget cannot be calculated."; } public string Id { get { return this.doNotUseId; } set { this.doNotUseId = value; OnPropertyChanged(); BucketCode = Id; } } public Type WidgetType => GetType(); public void Initialise(MultiInstanceWidgetState state, ILogger logger) { } public override void Update([NotNull] params object[] input) { base.Update(input); DetailedText = BucketCode; if (!Enabled) { ToolTip = this.disabledToolTip; } } } }```
185e737f-cb92-4342-96b0-e04507ed1822
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TicTacToe.Core; using TicTacToe.Web.Data; using TicTacToe.Web.ViewModels; namespace TicTacToe.Controllers { public class GameController : Controller { private ApplicationDbContext context; public ApplicationDbContext Context => context ?? (context = new ApplicationDbContext()); public ActionResult Index() { //var context = new ApplicationDbContext(); //var game = new Game {Player = "123"}; //var field = new Field() {Game = game}; //game.Field = field; //context.Games.Add(game); //context.Commit(); //context.Dispose(); return View(); } public ActionResult Play(string playerName) { if (string.IsNullOrEmpty(playerName)) return View("Index"); var game = new Game(); game.CreateField(); game.Player = playerName; Context.Games.Add(game); return View(game); } public JsonResult Turn(TurnClientViewModel turn) { return Json(turn); } public ActionResult About() { var context = new ApplicationDbContext(); var games = context.Games.ToArray(); context.Dispose(); ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } protected override void Dispose(bool disposing) { context?.Dispose(); base.Dispose(disposing); } } }``` Add missing Commit, when game starts.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TicTacToe.Core; using TicTacToe.Web.Data; using TicTacToe.Web.ViewModels; namespace TicTacToe.Controllers { public class GameController : Controller { private ApplicationDbContext context; public ApplicationDbContext Context => context ?? (context = new ApplicationDbContext()); public ActionResult Index() { //var context = new ApplicationDbContext(); //var game = new Game {Player = "123"}; //var field = new Field() {Game = game}; //game.Field = field; //context.Games.Add(game); //context.Commit(); //context.Dispose(); return View(); } public ActionResult Play(string playerName) { if (string.IsNullOrEmpty(playerName)) return View("Index"); var game = new Game(); game.CreateField(); game.Player = playerName; Context.Games.Add(game); Context.Commit(); return View(game); } public JsonResult Turn(TurnClientViewModel turn) { return Json(turn); } public ActionResult About() { var context = new ApplicationDbContext(); var games = context.Games.ToArray(); context.Dispose(); ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } protected override void Dispose(bool disposing) { context?.Dispose(); base.Dispose(disposing); } } }```
0c16e57a-15a8-4532-934e-2c5f401d4500
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Autofac.Test.Features.OpenGenerics { public class OpenGenericDelegateTests { private interface IInterfaceA<T> { } private class ImplementationA<T> : IInterfaceA<T> { } [Fact] public void CanResolveByGenericInterface() { var builder = new ContainerBuilder(); builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types))) .As(typeof(IInterfaceA<>)); var container = builder.Build(); var instance = container.Resolve<IInterfaceA<string>>(); var implementedType = instance.GetType().GetGenericTypeDefinition(); Assert.Equal(typeof(ImplementationA<>), implementedType); } } } ``` Add negative test for the registration source.
```c# using System; using System.Collections.Generic; using System.Text; using Autofac.Core; using Autofac.Core.Registration; using Xunit; namespace Autofac.Test.Features.OpenGenerics { public class OpenGenericDelegateTests { private interface IInterfaceA<T> { } private interface IInterfaceB<T> { } private class ImplementationA<T> : IInterfaceA<T> { } [Fact] public void CanResolveByGenericInterface() { var builder = new ContainerBuilder(); builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types))) .As(typeof(IInterfaceA<>)); var container = builder.Build(); var instance = container.Resolve<IInterfaceA<string>>(); var implementedType = instance.GetType().GetGenericTypeDefinition(); Assert.Equal(typeof(ImplementationA<>), implementedType); } [Fact] public void DoesNotResolveForDifferentGenericService() { var builder = new ContainerBuilder(); builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types))) .As(typeof(IInterfaceA<>)); var container = builder.Build(); Assert.Throws<ComponentNotRegisteredException>(() => container.Resolve<IInterfaceB<string>>()); } } } ```
e4513202-9fc4-436a-b7b7-f432d5b5cab1
{ "language": "C#" }
```c# namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion { using System; using TestClasses; using Xunit; public class WhenMappingToDateTimes { [Fact] public void ShouldMapANullableDateTimeToADateTime() { var source = new PublicProperty<DateTime?> { Value = DateTime.Today }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>(); result.Value.ShouldBe(DateTime.Today); } [Fact] public void ShouldMapAYearMonthDayStringToADateTime() { var source = new PublicProperty<string> { Value = "2016/06/08" }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>(); result.Value.ShouldBe(new DateTime(2016, 06, 08)); } } } ``` Test coverage for unparseable string -> DateTime conversion
```c# namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion { using System; using Shouldly; using TestClasses; using Xunit; public class WhenMappingToDateTimes { [Fact] public void ShouldMapANullableDateTimeToADateTime() { var source = new PublicProperty<DateTime?> { Value = DateTime.Today }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>(); result.Value.ShouldBe(DateTime.Today); } [Fact] public void ShouldMapAYearMonthDayStringToADateTime() { var source = new PublicProperty<string> { Value = "2016/06/08" }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>(); result.Value.ShouldBe(new DateTime(2016, 06, 08)); } [Fact] public void ShouldMapAnUnparseableStringToANullableDateTime() { var source = new PublicProperty<string> { Value = "OOH OOH OOH" }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime?>>(); result.Value.ShouldBeNull(); } } } ```
941a9e14-7590-4d60-a4c4-5381d9d04432
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using WalletWasabi.Bases; using WalletWasabi.Coins; namespace WalletWasabi.BlockchainAnalysis { public class Cluster : NotifyPropertyChangedBase { private List<SmartCoin> Coins { get; set; } private string _labels; public Cluster(params SmartCoin[] coins) : this(coins as IEnumerable<SmartCoin>) { } public Cluster(IEnumerable<SmartCoin> coins) { Coins = coins.ToList(); Labels = string.Join(", ", KnownBy); } public string Labels { get => _labels; private set => RaiseAndSetIfChanged(ref _labels, value); } public int Size => Coins.Count(); public IEnumerable<string> KnownBy => Coins.SelectMany(x => x.Label.Labels).Distinct(StringComparer.OrdinalIgnoreCase); public void Merge(Cluster clusters) => Merge(clusters.Coins); public void Merge(IEnumerable<SmartCoin> coins) { var insertPosition = 0; foreach (var coin in coins.ToList()) { if (!Coins.Contains(coin)) { Coins.Insert(insertPosition++, coin); } coin.Clusters = this; } if (insertPosition > 0) // at least one element was inserted { Labels = string.Join(", ", KnownBy); } } } } ``` Use Count instead of Count()
```c# using System; using System.Collections.Generic; using System.Linq; using WalletWasabi.Bases; using WalletWasabi.Coins; namespace WalletWasabi.BlockchainAnalysis { public class Cluster : NotifyPropertyChangedBase { private List<SmartCoin> Coins { get; set; } private string _labels; public Cluster(params SmartCoin[] coins) : this(coins as IEnumerable<SmartCoin>) { } public Cluster(IEnumerable<SmartCoin> coins) { Coins = coins.ToList(); Labels = string.Join(", ", KnownBy); } public string Labels { get => _labels; private set => RaiseAndSetIfChanged(ref _labels, value); } public int Size => Coins.Count; public IEnumerable<string> KnownBy => Coins.SelectMany(x => x.Label.Labels).Distinct(StringComparer.OrdinalIgnoreCase); public void Merge(Cluster clusters) => Merge(clusters.Coins); public void Merge(IEnumerable<SmartCoin> coins) { var insertPosition = 0; foreach (var coin in coins.ToList()) { if (!Coins.Contains(coin)) { Coins.Insert(insertPosition++, coin); } coin.Clusters = this; } if (insertPosition > 0) // at least one element was inserted { Labels = string.Join(", ", KnownBy); } } } } ```
95a1f45c-bba4-44cf-a11f-293b6e6fb77d
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } } ``` Update server side API for single multiple answer question
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } } ```
c31ea9bf-d0f7-43c2-bc01-2a1ef5e49b62
{ "language": "C#" }
```c# // Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace NOpenCL.Test { internal static class TestCategories { public const string RequireGpu = nameof(RequireGpu); } }``` Fix a build warning for missing blank line at end of file
```c# // Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace NOpenCL.Test { internal static class TestCategories { public const string RequireGpu = nameof(RequireGpu); } } ```
baef018b-15c5-4e7d-8cec-73d95b4c93d2
{ "language": "C#" }
```c# using System.Threading.Tasks; using Windows.ApplicationModel.Activation; namespace Sample { sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); } public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); await Task.Yield(); } } } ``` Replace another Task.Yield with Task.CompletedTask.
```c# using System.Threading.Tasks; using Windows.ApplicationModel.Activation; namespace Sample { sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); } public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); return Task.CompletedTask; } } } ```
4bc85fce-a030-4083-9d34-661453b7dcf9
{ "language": "C#" }
```c# @page "{id}" @model SessionModel <ol class="breadcrumb"> <li><a asp-page="/Index">Agenda</a></li> <li><a asp-page="/Index" asp-route-day="@Model.DayOffset">Day @(Model.DayOffset + 1)</a></li> <li class="active">@Model.Session.Title</li> </ol> <h1>@Model.Session.Title</h1> <span class="label label-default">@Model.Session.Track?.Name</span> @foreach (var speaker in Model.Session.Speakers) { <em><a asp-page="Speaker" asp-route-id="@speaker.ID">@speaker.Name</a></em> } <p>@Html.Raw(Model.Session.Abstract)</p> <form method="post"> <input type="hidden" name="sessionId" value="@Model.Session.ID" /> <p> <a authz-policy="Admin" asp-page="/Admin/EditSession" asp-route-id="@Model.Session.ID" class="btn btn-default btn-sm">Edit</a> @if (Model.IsFavorite) { <button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from Favorites</button> } else { <button authz="true" type="submit" class="btn btn-primary">Add to Favorites</button> } </p> </form>``` Change text from favorites to "My Agenda"
```c# @page "{id}" @model SessionModel <ol class="breadcrumb"> <li><a asp-page="/Index">Agenda</a></li> <li><a asp-page="/Index" asp-route-day="@Model.DayOffset">Day @(Model.DayOffset + 1)</a></li> <li class="active">@Model.Session.Title</li> </ol> <h1>@Model.Session.Title</h1> <span class="label label-default">@Model.Session.Track?.Name</span> @foreach (var speaker in Model.Session.Speakers) { <em><a asp-page="Speaker" asp-route-id="@speaker.ID">@speaker.Name</a></em> } <p>@Html.Raw(Model.Session.Abstract)</p> <form method="post"> <input type="hidden" name="sessionId" value="@Model.Session.ID" /> <p> <a authz-policy="Admin" asp-page="/Admin/EditSession" asp-route-id="@Model.Session.ID" class="btn btn-default btn-sm">Edit</a> @if (Model.IsFavorite) { <button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from My Agenda</button> } else { <button authz="true" type="submit" class="btn btn-primary">Add to My Agenda</button> } </p> </form>```
8b38aee1-5407-4c86-b5aa-034468b9ae64
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using Affecto.IdentityManagement.ApplicationServices.Model; using Affecto.IdentityManagement.Interfaces.Model; using Affecto.Mapping.AutoMapper; using AutoMapper; namespace Affecto.IdentityManagement.ApplicationServices.Mapping { internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role> { protected override void ConfigureMaps() { Func<Querying.Data.Permission, IPermission> permissionCreator = o => new Permission(); Mapper.CreateMap<Querying.Data.Permission, IPermission>().ConvertUsing(permissionCreator); Mapper.CreateMap<Querying.Data.Permission, Permission>(); Mapper.CreateMap<Querying.Data.Role, Role>() .ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<IPermission>>(c.Permissions.ToList()))); } } }``` Remove interface mapping from role mapper
```c# using System.Collections.Generic; using System.Linq; using Affecto.IdentityManagement.ApplicationServices.Model; using Affecto.Mapping.AutoMapper; using AutoMapper; namespace Affecto.IdentityManagement.ApplicationServices.Mapping { internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role> { protected override void ConfigureMaps() { Mapper.CreateMap<Querying.Data.Permission, Permission>(); Mapper.CreateMap<Querying.Data.Role, Role>() .ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<Permission>>(c.Permissions.ToList()))); } } }```
8423388d-d462-4298-ac4a-63c592f65df9
{ "language": "C#" }
```c# using System; using Autofac; namespace AGS.Engine.IOS { public class AGSEngineIOS { private static IOSAssemblies _assembly; public static void Init() { OpenTK.Toolkit.Init(); var device = new IOSDevice(_assembly); AGSGame.Device = device; //Resolver.Override(resolver => resolver.Builder.RegisterType<AndroidGameWindowSize>().SingleInstance().As<IGameWindowSize>()); Resolver.Override(resolver => resolver.Builder.RegisterType<ALAudioBackend>().SingleInstance().As<IAudioBackend>()); } public static void SetAssembly() { _assembly = new IOSAssemblies(); } } } ``` Fix Autofac crash due to linker stripping out a function used by reflection only
```c# using System; using Autofac; namespace AGS.Engine.IOS { public class AGSEngineIOS { private static IOSAssemblies _assembly; public static void Init() { // On IOS, when the mono linker is enabled (and it's enabled by default) it strips out all parts of // the framework which are not in use. The linker does not support reflection, however, therefore it // does not recognize the call to 'GetRuntimeMethod(nameof(Convert.ChangeType)' (which is called from // a method in this Autofac in ConstructorParameterBinding class, ConvertPrimitiveType method) // as using the 'Convert.ChangeType' method and strips it away unless it's // explicitly used somewhere else, crashing Autofac if that method is called. // Therefore, by explicitly calling it here, we're playing nicely with the linker and making sure // Autofac works on IOS. Convert.ChangeType((object)1234f, typeof(float)); OpenTK.Toolkit.Init(); var device = new IOSDevice(_assembly); AGSGame.Device = device; //Resolver.Override(resolver => resolver.Builder.RegisterType<AndroidGameWindowSize>().SingleInstance().As<IGameWindowSize>()); Resolver.Override(resolver => resolver.Builder.RegisterType<ALAudioBackend>().SingleInstance().As<IAudioBackend>()); } public static void SetAssembly() { _assembly = new IOSAssemblies(); } } } ```
993c09ba-f4bd-4d87-9aec-bfcd46a2c841
{ "language": "C#" }
```c# using System; using System.IO; using Newtonsoft.Json; namespace Scanner { using System.Collections.Generic; public class BackingStore { private string backingStoreName; public BackingStore(string backingStoreName) { this.backingStoreName = backingStoreName; } public IEnumerable<Child> GetAll() { string json = File.ReadAllText(GetBackingStoreFilename()); return JsonConvert.DeserializeObject<IEnumerable<Child>>(json); } public void SaveAll(IEnumerable<Child> children) { string json = JsonConvert.SerializeObject(children); var applicationFile = GetBackingStoreFilename(); File.WriteAllText(applicationFile, json); } private static string GetBackingStoreFilename() { var applicationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Scanner"); Directory.CreateDirectory(applicationFolder); var applicationFile = Path.Combine(applicationFolder, "children.json"); return applicationFile; } } }``` Make sure we read the backing store name properly.
```c# using System; using System.IO; using Newtonsoft.Json; namespace Scanner { using System.Collections.Generic; public class BackingStore { private string backingStoreName; public BackingStore(string backingStoreName) { this.backingStoreName = backingStoreName; } public IEnumerable<Child> GetAll() { string json = File.ReadAllText(GetBackingStoreFilename()); return JsonConvert.DeserializeObject<IEnumerable<Child>>(json); } public void SaveAll(IEnumerable<Child> children) { string json = JsonConvert.SerializeObject(children); var applicationFile = GetBackingStoreFilename(); File.WriteAllText(applicationFile, json); } private string GetBackingStoreFilename() { var applicationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Scanner"); Directory.CreateDirectory(applicationFolder); var applicationFile = Path.Combine(applicationFolder, string.Format("{0}.json", backingStoreName)); return applicationFile; } } }```
e9663a3c-9cb8-4979-8634-eafd52c08304
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using HarryPotterUnity.Tween; using HarryPotterUnity.Utils; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.Generic { public abstract class GenericSpell : GenericCard { private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f); protected sealed override void OnClickAction(List<GenericCard> targets) { Enable(); PreviewSpell(); Player.Hand.Remove(this); Player.Discard.Add(this); SpellAction(targets); } protected abstract void SpellAction(List<GenericCard> targets); private void PreviewSpell() { State = CardStates.Discarded; var rotate180 = Player.OppositePlayer.IsLocalPlayer ? TweenQueue.RotationType.Rotate180 : TweenQueue.RotationType.NoRotate; UtilManager.TweenQueue.AddTweenToQueue(new MoveTween(gameObject, SpellOffset, 0.5f, 0f, FlipStates.FaceUp, rotate180, State)); } } }``` Add 0.6 seconds preview time for spells
```c# using System.Collections; using System.Collections.Generic; using HarryPotterUnity.Tween; using HarryPotterUnity.Utils; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.Generic { public abstract class GenericSpell : GenericCard { private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f); protected sealed override void OnClickAction(List<GenericCard> targets) { Enable(); PreviewSpell(); Player.Hand.Remove(this); Player.Discard.Add(this); SpellAction(targets); } protected abstract void SpellAction(List<GenericCard> targets); private void PreviewSpell() { State = CardStates.Discarded; var rotate180 = Player.OppositePlayer.IsLocalPlayer ? TweenQueue.RotationType.Rotate180 : TweenQueue.RotationType.NoRotate; UtilManager.TweenQueue.AddTweenToQueue(new MoveTween(gameObject, SpellOffset, 0.5f, 0f, FlipStates.FaceUp, rotate180, State, 0.6f)); } } }```
a9ad0e7d-98ed-4629-aa20-c05fda81ff7e
{ "language": "C#" }
```c# using Microsoft.Azure.ServiceBus; using System; using System.Collections.Generic; using QueueMessage = Storage.Net.Messaging.QueueMessage; namespace Storage.Net.Microsoft.Azure.ServiceBus { static class Converter { public static Message ToMessage(QueueMessage message) { if(message == null) throw new ArgumentNullException(nameof(message)); var result = new Message(message.Content); if(message.Properties != null && message.Properties.Count > 0) { foreach(KeyValuePair<string, string> prop in message.Properties) { result.UserProperties.Add(prop.Key, prop.Value); } } return result; } public static QueueMessage ToQueueMessage(Message message) { string id = message.MessageId ?? message.SystemProperties.SequenceNumber.ToString(); var result = new QueueMessage(id, message.Body); result.DequeueCount = message.SystemProperties.DeliveryCount; if(message.UserProperties != null && message.UserProperties.Count > 0) { foreach(KeyValuePair<string, object> pair in message.UserProperties) { result.Properties[pair.Key] = pair.Value == null ? null : pair.Value.ToString(); } } return result; } } } ``` Add message id to storage convert process
```c# using Microsoft.Azure.ServiceBus; using System; using System.Collections.Generic; using QueueMessage = Storage.Net.Messaging.QueueMessage; namespace Storage.Net.Microsoft.Azure.ServiceBus { static class Converter { public static Message ToMessage(QueueMessage message) { if(message == null) throw new ArgumentNullException(nameof(message)); var result = new Message(message.Content) { MessageId = message.Id }; if(message.Properties != null && message.Properties.Count > 0) { foreach(KeyValuePair<string, string> prop in message.Properties) { result.UserProperties.Add(prop.Key, prop.Value); } } return result; } public static QueueMessage ToQueueMessage(Message message) { string id = message.MessageId ?? message.SystemProperties.SequenceNumber.ToString(); var result = new QueueMessage(id, message.Body); result.DequeueCount = message.SystemProperties.DeliveryCount; if(message.UserProperties != null && message.UserProperties.Count > 0) { foreach(KeyValuePair<string, object> pair in message.UserProperties) { result.Properties[pair.Key] = pair.Value == null ? null : pair.Value.ToString(); } } return result; } } } ```
c557a60f-6982-449e-940a-9705535d60c8
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using Discord; using Discord.Commands; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using NoAdsHere.Database; using NoAdsHere.Database.Models.GuildSettings; using NoAdsHere.Common; using NoAdsHere.Common.Preconditions; using NoAdsHere.Services.AntiAds; namespace NoAdsHere.Commands.Blocks { [Name("Blocks"), Group("Blocks")] public class BlockModule : ModuleBase { private readonly MongoClient _mongo; public BlockModule(IServiceProvider provider) { _mongo = provider.GetService<MongoClient>(); } [Command("Invites"), Alias("Invite")] [RequirePermission(AccessLevel.HighModerator)] public async Task Invites(bool setting) { bool success; if (setting) success = await AntiAds.TryEnableGuild(BlockType.InstantInvite, Context.Guild.Id); else success = await AntiAds.TryDisableGuild(BlockType.InstantInvite, Context.Guild.Id); if (success) await ReplyAsync($":white_check_mark: Discord Invite Blockings have been set to {setting}. {(setting ? "Please ensure that the bot can ManageMessages in the required channels" : "")} :white_check_mark:"); else await ReplyAsync($":exclamation: Discord Invite Blocks already set to {setting} :exclamation:"); } } }``` Clean the Blocks Module of unused code
```c# using System.Threading.Tasks; using Discord.Commands; using NoAdsHere.Common; using NoAdsHere.Common.Preconditions; using NoAdsHere.Services.AntiAds; namespace NoAdsHere.Commands.Blocks { [Name("Blocks"), Group("Blocks")] public class BlockModule : ModuleBase { [Command("Invite")] [RequirePermission(AccessLevel.HighModerator)] public async Task Invites(bool setting) { bool success; if (setting) success = await AntiAds.TryEnableGuild(BlockType.InstantInvite, Context.Guild.Id); else success = await AntiAds.TryDisableGuild(BlockType.InstantInvite, Context.Guild.Id); if (success) await ReplyAsync($":white_check_mark: Discord Invite Blockings have been set to {setting}. {(setting ? "Please ensure that the bot can ManageMessages in the required channels" : "")} :white_check_mark:"); else await ReplyAsync($":exclamation: Discord Invite Blocks already set to {setting} :exclamation:"); } } }```
f3e4d044-a434-42ec-9e47-8d4a039e10f0
{ "language": "C#" }
```c# using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using ClientSamples.CachingTools; namespace Tavis.PrivateCache { public class CacheEntry { public PrimaryCacheKey Key { get; private set; } public HttpHeaderValueCollection<string> VaryHeaders { get; private set; } internal CacheEntry(PrimaryCacheKey key, HttpHeaderValueCollection<string> varyHeaders) { Key = key; VaryHeaders = varyHeaders; } public string CreateSecondaryKey(HttpRequestMessage request) { var key = ""; foreach (var h in VaryHeaders.OrderBy(v => v)) // Sort the vary headers so that ordering doesn't generate different stored variants { if (h != "*") { key += h + ":" + String.Join(",", request.Headers.GetValues(h)); } else { key += "*"; } } return key.ToLower(); } public CacheContent CreateContent(HttpResponseMessage response) { return new CacheContent() { CacheEntry = this, Key = CreateSecondaryKey(response.RequestMessage), HasValidator = response.Headers.ETag != null || (response.Content != null && response.Content.Headers.LastModified != null), Expires = HttpCache.GetExpireDate(response), CacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(), Response = response, }; } } }``` Switch to StringBuilder for speed.
```c# using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using ClientSamples.CachingTools; namespace Tavis.PrivateCache { public class CacheEntry { public PrimaryCacheKey Key { get; private set; } public HttpHeaderValueCollection<string> VaryHeaders { get; private set; } internal CacheEntry(PrimaryCacheKey key, HttpHeaderValueCollection<string> varyHeaders) { Key = key; VaryHeaders = varyHeaders; } public string CreateSecondaryKey(HttpRequestMessage request) { var key = new StringBuilder(); foreach (var h in VaryHeaders.OrderBy(v => v)) // Sort the vary headers so that ordering doesn't generate different stored variants { if (h != "*") { key.Append(h).Append(':'); bool addedOne = false; foreach (var val in request.Headers.GetValues(h)) { key.Append(val).Append(','); addedOne = true; } if (addedOne) { key.Length--; // truncate trailing comma. } } else { key.Append('*'); } } return key.ToString().ToLowerInvariant(); } public CacheContent CreateContent(HttpResponseMessage response) { return new CacheContent() { CacheEntry = this, Key = CreateSecondaryKey(response.RequestMessage), HasValidator = response.Headers.ETag != null || (response.Content != null && response.Content.Headers.LastModified != null), Expires = HttpCache.GetExpireDate(response), CacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(), Response = response, }; } } } ```
edcc069a-2d49-44e2-9794-a489ed23d6ab
{ "language": "C#" }
```c# using NBi.Core.Evaluate; using NBi.Core.ResultSet; using NBi.Core.Transformation; using NBi.Xml.Variables; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace NBi.Xml.Items.Calculation { [XmlType("")] public class ExpressionXml: IColumnExpression { [Obsolete("Use the attribute Script in place of Value")] [XmlText()] public string Value { get => ShouldSerializeValue() ? Script.Code : null; set => Script = new ScriptXml() { Language = LanguageType.NCalc, Code = value }; } public bool ShouldSerializeValue() => Script?.Language == LanguageType.NCalc; [XmlElement("script")] public ScriptXml Script { get; set; } public bool ShouldSerializeScript() => Script?.Language != LanguageType.NCalc; [XmlIgnore()] public LanguageType Language { get => ShouldSerializeValue() ? LanguageType.NCalc : Script.Language; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("column-index")] [DefaultValue(0)] public int Column { get; set; } [XmlAttribute("type")] [DefaultValue(ColumnType.Text)] public ColumnType Type { get; set; } [XmlAttribute("tolerance")] [DefaultValue("")] public string Tolerance { get; set; } } } ``` Fix some xml parsing issues
```c# using NBi.Core.Evaluate; using NBi.Core.ResultSet; using NBi.Core.Transformation; using NBi.Xml.Variables; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace NBi.Xml.Items.Calculation { [XmlType("")] public class ExpressionXml: IColumnExpression { [XmlText()] public string Value { get => Script.Code; set => Script.Code = value; } public bool ShouldSerializeValue() => Script.Language == LanguageType.NCalc; [XmlElement("script")] public ScriptXml Script { get; set; } public bool ShouldSerializeScript() => Script.Language != LanguageType.NCalc; [XmlIgnore()] public LanguageType Language { get => ShouldSerializeValue() ? LanguageType.NCalc : Script.Language; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("column-index")] [DefaultValue(0)] public int Column { get; set; } [XmlAttribute("type")] [DefaultValue(ColumnType.Text)] public ColumnType Type { get; set; } [XmlAttribute("tolerance")] [DefaultValue("")] public string Tolerance { get; set; } public ExpressionXml() { Script = new ScriptXml() { Language = LanguageType.NCalc }; } } } ```
0f7565e2-cec4-4641-a4ff-ecd28715977c
{ "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. using Microsoft.AspNet.Builder; using Microsoft.Framework.DependencyInjection; namespace TagHelpersWebSite { public class Startup { public void Configure(IApplicationBuilder app) { var configuration = app.GetTestConfiguration(); app.UseServices(services => { services.AddMvc(configuration); }); app.UseMvc(); } } } ``` Update new test to use UsePerRequestServices
```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. using Microsoft.AspNet.Builder; using Microsoft.Framework.DependencyInjection; namespace TagHelpersWebSite { public class Startup { public void Configure(IApplicationBuilder app) { var configuration = app.GetTestConfiguration(); app.UsePerRequestServices(services => { services.AddMvc(configuration); }); app.UseMvc(); } } } ```
236a7e86-8505-43bc-b9da-06eca7acec71
{ "language": "C#" }
```c# using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = $"About {AssemblyTitle}"; labelProductName.Text = AssemblyTitle; labelVersion.Text = AssemblyVersion; lastUpdatedBox.Text = LastUpdatedDate.ToString(); linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } public static string AssemblyTitle { get; } = "Vigilant Cupcake"; public static string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }``` Reduce information displayed in about box
```c# using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = $"About {AssemblyTitle}"; labelProductName.Text = AssemblyTitle; labelVersion.Text = AssemblyVersion; lastUpdatedBox.Text = LastUpdatedDate.ToString(); linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } public static string AssemblyTitle { get; } = "Vigilant Cupcake"; public static string AssemblyVersion { get { var version = Assembly.GetExecutingAssembly().GetName().Version; return $"{version.Major}.{version.Minor}.{version.Revision}"; } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }```
78d57e4c-f02f-4fc2-bf98-a4606f33a267
{ "language": "C#" }
```c# using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = $"About {AssemblyTitle}"; labelProductName.Text = AssemblyTitle; labelVersion.Text = AssemblyVersion; lastUpdatedBox.Text = LastUpdatedDate.ToString(); linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } public static string AssemblyTitle { get; } = "Vigilant Cupcake"; public static string AssemblyVersion { get { var version = Assembly.GetExecutingAssembly().GetName().Version; return $"{version.Major}.{version.Minor}.{version.Revision}"; } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }``` Fix wrong attribute for about box
```c# using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = $"About {AssemblyTitle}"; labelProductName.Text = AssemblyTitle; labelVersion.Text = AssemblyVersion; lastUpdatedBox.Text = LastUpdatedDate.ToString(); linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } public static string AssemblyTitle { get; } = "Vigilant Cupcake"; public static string AssemblyVersion { get { var version = Assembly.GetExecutingAssembly().GetName().Version; return $"{version.Major}.{version.Minor}.{version.Build}"; } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }```
bab609a5-e62d-420c-b9ef-59fc2ab4dc30
{ "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("Digital Color Meter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Digital Color Meter")] [assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")] [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("ca199dd4-2017-4ee7-808c-3747101e04b1")] // 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")] ``` Add license info in assembly.
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Digital Color Meter")] [assembly: AssemblyDescription("Released under the MIT License")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Digital Color Meter")] [assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")] [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("ca199dd4-2017-4ee7-808c-3747101e04b1")] // 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")] ```
90445758-cedd-4323-ba86-849cf73b18f0
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using Newtonsoft.Json; namespace osu.Framework.IO.Network { /// <summary> /// A web request with a specific JSON response format. /// </summary> /// <typeparam name="T">the response format.</typeparam> public class JsonWebRequest<T> : WebRequest { public JsonWebRequest(string url = null, params object[] args) : base(url, args) { base.Finished += finished; } private void finished(WebRequest request, Exception e) { try { deserialisedResponse = JsonConvert.DeserializeObject<T>(ResponseString); } catch (Exception se) { e = e == null ? se : new AggregateException(e, se); } Finished?.Invoke(this, e); } private T deserialisedResponse; public T ResponseObject => deserialisedResponse; /// <summary> /// Request has finished with success or failure. Check exception == null for success. /// </summary> public new event RequestCompleteHandler<T> Finished; } } ``` Use the correct Accept type for json requests
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Net; using Newtonsoft.Json; namespace osu.Framework.IO.Network { /// <summary> /// A web request with a specific JSON response format. /// </summary> /// <typeparam name="T">the response format.</typeparam> public class JsonWebRequest<T> : WebRequest { public JsonWebRequest(string url = null, params object[] args) : base(url, args) { base.Finished += finished; } protected override HttpWebRequest CreateWebRequest(string requestString = null) { var req = base.CreateWebRequest(requestString); req.Accept = @"application/json"; return req; } private void finished(WebRequest request, Exception e) { try { deserialisedResponse = JsonConvert.DeserializeObject<T>(ResponseString); } catch (Exception se) { e = e == null ? se : new AggregateException(e, se); } Finished?.Invoke(this, e); } private T deserialisedResponse; public T ResponseObject => deserialisedResponse; /// <summary> /// Request has finished with success or failure. Check exception == null for success. /// </summary> public new event RequestCompleteHandler<T> Finished; } } ```
af825548-ec55-4af7-9e60-39463c74abcd
{ "language": "C#" }
```c# using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(SFA.DAS.EmployerUsers.Api.Startup))] namespace SFA.DAS.EmployerUsers.Api { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }``` Add TLS change to make the call to the Audit api work
```c# using System.Net; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(SFA.DAS.EmployerUsers.Api.Startup))] namespace SFA.DAS.EmployerUsers.Api { public partial class Startup { public void Configuration(IAppBuilder app) { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; ConfigureAuth(app); } } }```
b7d2cf95-3e4b-4a05-85fe-9c4346b614d8
{ "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("TSRandom")] [assembly: AssemblyDescription("Thread safe random number generator")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TSRandom")] [assembly: AssemblyCopyright("Copyright © Soleil Rojas 2017")] [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("82f2ca28-6157-41ff-b644-2ef357ee4d6c")] // 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 the assembly version to use wildcard
```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("TSRandom")] [assembly: AssemblyDescription("Thread safe random number generator")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TSRandom")] [assembly: AssemblyCopyright("Copyright © Soleil Rojas 2017")] [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("82f2ca28-6157-41ff-b644-2ef357ee4d6c")] // 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.*")] [assembly: AssemblyFileVersion("1.0.0.0")] ```
688ecbc5-616e-45a3-9eb9-3c46e99f695c
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Http; using Obsidian.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Authentication; using Obsidian.Application.OAuth20; namespace Obsidian.Services { public class SignInService : ISignInService { private readonly IHttpContextAccessor _accessor; const string Scheme = "Obsidian.Cookie"; public SignInService(IHttpContextAccessor accessor) { _accessor = accessor; } public async Task CookieSignInAsync(User user, bool isPersistent) { await CookieSignOutCurrentUserAsync(); var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.UserName) }; var identity = new ClaimsIdentity(claims); var principal = new ClaimsPrincipal(identity); var context = _accessor.HttpContext; var props = new AuthenticationProperties{ IsPersistent = isPersistent }; await context.Authentication.SignInAsync(Scheme, principal, props); } public async Task CookieSignOutCurrentUserAsync() => await _accessor.HttpContext.Authentication.SignOutAsync(Scheme); } } ``` Revert "keep username only in sinin cookie"
```c# using Microsoft.AspNetCore.Http; using Obsidian.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Authentication; using Obsidian.Application.OAuth20; namespace Obsidian.Services { public class SignInService : ISignInService { private readonly IHttpContextAccessor _accessor; const string Scheme = "Obsidian.Cookie"; public SignInService(IHttpContextAccessor accessor) { _accessor = accessor; } public async Task CookieSignInAsync(User user, bool isPersistent) { await CookieSignOutCurrentUserAsync(); var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName) }; var identity = new ClaimsIdentity(claims); var principal = new ClaimsPrincipal(identity); var context = _accessor.HttpContext; var props = new AuthenticationProperties{ IsPersistent = isPersistent }; await context.Authentication.SignInAsync(Scheme, principal, props); } public async Task CookieSignOutCurrentUserAsync() => await _accessor.HttpContext.Authentication.SignOutAsync(Scheme); } } ```
27fc47c5-c972-4e87-a9a4-16d9a3d66440
{ "language": "C#" }
```c# #region Copyright and license // // <copyright file="AlwaysTests.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // 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. // // </license> #endregion namespace Delizious.Filtering { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class AlwaysTests { [TestMethod] public void Succeed__When_Value_Is_Null() { Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(null)); } [TestMethod] public void Succeed__When_Value_Is_An_Instance() { Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(new GenericParameterHelper())); } } } ``` Improve naming of tests to clearly indicate the feature to be tested
```c# #region Copyright and license // // <copyright file="AlwaysTests.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // 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. // // </license> #endregion namespace Delizious.Filtering { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class AlwaysTests { [TestMethod] public void Match_Succeeds_When_Value_To_Match_Is_Null() { Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(null)); } [TestMethod] public void Match_Succeeds_When_Value_To_Match_Is_An_Instance() { Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(new GenericParameterHelper())); } } } ```
6f44a965-edd4-4ab3-a98e-c73b0cc969ed
{ "language": "C#" }
```c# using NUnit.Framework; [assembly: Category("IntegrationTest")] [assembly: Parallelizable(ParallelScope.Fixtures)] [assembly: LevelOfParallelism(32)]``` Reduce concurrency (not eliminate) in integration tests so that starting up a test suite run doesn't soak up all the threads in our thread pool.
```c# using NUnit.Framework; [assembly: Category("IntegrationTest")] [assembly: Parallelizable(ParallelScope.Fixtures)] [assembly: LevelOfParallelism(2)]```
a4311705-5830-419b-9c02-3a336c86baa8
{ "language": "C#" }
```c# void DownloadAudienceNetwork (Artifact artifact) { var podSpec = artifact.PodSpecs [0]; var id = podSpec.Name; var version = podSpec.Version; var url = $"https://origincache.facebook.com/developers/resources/?id={id}-{version}.zip"; var basePath = $"./externals/{id}"; DownloadFile (url, $"{basePath}.zip", new Cake.Xamarin.Build.DownloadFileSettings { UserAgent = "curl/7.43.0" }); Unzip ($"{basePath}.zip", $"{basePath}"); CopyDirectory ($"{basePath}/Dynamic/{id}.framework", $"./externals/{id}.framework"); } ``` Use same url Facebook uses to download bits
```c# void DownloadAudienceNetwork (Artifact artifact) { var podSpec = artifact.PodSpecs [0]; var id = podSpec.Name; var version = podSpec.Version; var url = $"https://developers.facebook.com/resources/{id}-{version}.zip"; var basePath = $"./externals/{id}"; DownloadFile (url, $"{basePath}.zip", new Cake.Xamarin.Build.DownloadFileSettings { UserAgent = "curl/7.43.0" }); Unzip ($"{basePath}.zip", $"{basePath}"); CopyDirectory ($"{basePath}/Dynamic/{id}.framework", $"./externals/{id}.framework"); } ```
355782b3-128f-4abd-b5f7-8030603e6ade
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using NuGet.Packaging; namespace PackageExplorerViewModel.Utilities { public class TemporaryFile : IDisposable { public TemporaryFile(Stream stream, string extension) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (!string.IsNullOrWhiteSpace(extension) || extension[0] != '.') { extension = string.Empty; } FileName = Path.GetTempFileName() + extension; stream.CopyToFile(FileName); } public string FileName { get; } bool disposed; public void Dispose() { if (!disposed) { disposed = true; try { File.Delete(FileName); } catch // best effort { } } } } } ``` Fix check so file extension is preserved
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using NuGet.Packaging; namespace PackageExplorerViewModel.Utilities { public class TemporaryFile : IDisposable { public TemporaryFile(Stream stream, string extension) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (string.IsNullOrWhiteSpace(extension) || extension[0] != '.') { extension = string.Empty; } FileName = Path.GetTempFileName() + extension; stream.CopyToFile(FileName); } public string FileName { get; } bool disposed; public void Dispose() { if (!disposed) { disposed = true; try { File.Delete(FileName); } catch // best effort { } } } } } ```
fc38bde7-d0e7-4e96-a342-3cbcfdb580e6
{ "language": "C#" }
```c# using System.Threading; using System.Threading.Tasks; using Console = System.Console; namespace ConsoleWritePrettyOneDay.App { class Program { static void Main(string[] args) { Spinner.Wait(() => Thread.Sleep(5000), "waiting for sleep"); var task = Task.Run(() => Thread.Sleep(4000)); Spinner.Wait(task, "waiting for task"); Console.ReadLine(); } } } ``` Add message to press enter when sample App execution is complete
```c# using System.Threading; using System.Threading.Tasks; using Console = System.Console; namespace ConsoleWritePrettyOneDay.App { class Program { static void Main(string[] args) { Spinner.Wait(() => Thread.Sleep(5000), "waiting for sleep"); var task = Task.Run(() => Thread.Sleep(4000)); Spinner.Wait(task, "waiting for task"); Console.WriteLine(); Console.WriteLine("Press [enter] to exit."); Console.ReadLine(); } } } ```
9dab8f34-4524-49b8-a56e-3c1de550ce8d
{ "language": "C#" }
```c# using System.Windows; namespace twitch_tv_viewer.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Edit_Click(object sender, RoutedEventArgs e) => new Edit().ShowDialog(); private void Add_Click(object sender, RoutedEventArgs e) => new Add().ShowDialog(); } } ``` Add simple binding for showing display of delete view
```c# using System.Windows; using System.Windows.Input; namespace twitch_tv_viewer.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Edit_Click(object sender, RoutedEventArgs e) => new Edit().ShowDialog(); private void Add_Click(object sender, RoutedEventArgs e) => new Add().ShowDialog(); private void Datagrid_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Delete) new Delete().ShowDialog(); } } } ```
6abb97e9-3d49-4f21-9b2d-538223c956d2
{ "language": "C#" }
```c# using System; namespace uSync8.Core.Dependency { [Flags] public enum DependencyFlags { None = 0, IncludeChildren = 2, IncludeAncestors = 4, IncludeDependencies = 8, IncludeViews = 16, IncludeMedia = 32, IncludeLinked = 64, IncludeMediaFiles = 128 } } ``` Add config to the dependency flags.
```c# using System; namespace uSync8.Core.Dependency { [Flags] public enum DependencyFlags { None = 0, IncludeChildren = 2, IncludeAncestors = 4, IncludeDependencies = 8, IncludeViews = 16, IncludeMedia = 32, IncludeLinked = 64, IncludeMediaFiles = 128, IncludeConfig = 256 } } ```
9f6664e8-cdca-4aff-895c-751974936532
{ "language": "C#" }
```c# using BmpListener.Extensions; using System; using System.Linq; namespace BmpListener.Bgp { public class CapabilityMultiProtocol : Capability { public CapabilityMultiProtocol(ArraySegment<byte> data) : base(data) { var afi = data.ToInt16(2); var safi = data.ElementAt(4); } } }``` Fix Multiprotocol AFI and SAFI decoding
```c# using System; namespace BmpListener.Bgp { public class CapabilityMultiProtocol : Capability { public CapabilityMultiProtocol(ArraySegment<byte> data) : base(data) { Decode(CapabilityValue); } public AddressFamily Afi { get; set; } public SubsequentAddressFamily Safi { get; set; } // RFC 4760 - Reserved (8 bit) field. SHOULD be set to 0 by the // sender and ignored by the receiver. public byte Res { get { return 0; } } public void Decode(ArraySegment<byte> data) { Array.Reverse(CapabilityValue.Array, data.Offset, 2); Afi = (AddressFamily)BitConverter.ToInt16(data.Array, data.Offset); Safi = (SubsequentAddressFamily)data.Array[data.Offset + 3]; } } }```
a599d2e4-87eb-496f-9220-9b1e8ff9d04b
{ "language": "C#" }
```c# using System; namespace Mammoth.Couscous.java.net { internal class URI { private readonly Uri _uri; internal URI(string uri) { try { _uri = new Uri(uri, UriKind.RelativeOrAbsolute); } catch (UriFormatException exception) { throw new URISyntaxException(exception.Message); } } internal URI(Uri uri) { _uri = uri; } internal bool isAbsolute() { return _uri.IsAbsoluteUri; } internal URL toURL() { return new URL(_uri.ToString()); } internal URI resolve(string relativeUri) { if (new URI(relativeUri).isAbsolute()) { return new URI(relativeUri); } else if (_uri.IsAbsoluteUri) { return new URI(new Uri(_uri, relativeUri)); } else { var path = _uri.ToString(); var lastSlashIndex = path.LastIndexOf("/"); var basePath = lastSlashIndex == -1 ? "." : path.Substring(0, lastSlashIndex + 1); return new URI(basePath + relativeUri); } } } } ``` Handle paths on Windows properly
```c# using System; namespace Mammoth.Couscous.java.net { internal class URI { private readonly Uri _uri; internal URI(string uri) { try { _uri = new Uri(uri, UriKind.RelativeOrAbsolute); } catch (UriFormatException exception) { throw new URISyntaxException(exception.Message); } } internal URI(Uri uri) { _uri = uri; } internal bool isAbsolute() { return _uri.IsAbsoluteUri; } internal URL toURL() { return new URL(_uri.ToString()); } internal URI resolve(string relativeUri) { if (new URI(relativeUri).isAbsolute()) { return new URI(relativeUri); } else if (_uri.IsAbsoluteUri) { return new URI(new Uri(_uri, relativeUri)); } else { var path = _uri.ToString(); var basePath = System.IO.Path.GetDirectoryName(path); return new URI(System.IO.Path.Combine(basePath, relativeUri)); } } } } ```
0ac085ee-43d1-4c46-8b79-2b3219bc95a1
{ "language": "C#" }
```c# // Copyright (c) the authors of nanoGames. All rights reserved. // Licensed under the MIT license. See LICENSE.txt in the project root. using NanoGames.Engine; using System.Collections.Generic; using System.Diagnostics; namespace NanoGames.Application { /// <summary> /// A view that measures and draws the current frames per second. /// </summary> internal sealed class FpsView : IView { private readonly Queue<long> _times = new Queue<long>(); /// <inheritdoc/> public void Update(Terminal terminal) { var fontSize = 6; var color = new Color(0.60, 0.35, 0.05); if (DebugMode.IsEnabled) { terminal.Graphics.Print(color, fontSize, new Vector(0, 0), "DEBUG"); } var time = Stopwatch.GetTimestamp(); if (Settings.Instance.ShowFps && _times.Count > 0) { var fps = (double)Stopwatch.Frequency * _times.Count / (time - _times.Peek()); var fpsString = ((int)(fps + 0.5)).ToString("D2"); terminal.Graphics.Print(color, fontSize, new Vector(GraphicsConstants.Width - fpsString.Length * fontSize, 0), fpsString); } if (_times.Count > 128) { _times.Dequeue(); } _times.Enqueue(time); } } } ``` Debug mode: Show the number of garbage collections
```c# // Copyright (c) the authors of nanoGames. All rights reserved. // Licensed under the MIT license. See LICENSE.txt in the project root. using NanoGames.Engine; using System.Collections.Generic; using System.Diagnostics; namespace NanoGames.Application { /// <summary> /// A view that measures and draws the current frames per second. /// </summary> internal sealed class FpsView : IView { private readonly Queue<long> _times = new Queue<long>(); /// <inheritdoc/> public void Update(Terminal terminal) { var fontSize = 6; var color = new Color(0.60, 0.35, 0.05); if (DebugMode.IsEnabled) { terminal.Graphics.Print(color, fontSize, new Vector(0, 0), "DEBUG"); for (int i = 0; i <= System.GC.MaxGeneration; ++i) { terminal.Graphics.Print(color, fontSize, new Vector(0, (i + 1) * fontSize), string.Format("GC{0}: {1}", i, System.GC.CollectionCount(i))); } } var time = Stopwatch.GetTimestamp(); if (Settings.Instance.ShowFps && _times.Count > 0) { var fps = (double)Stopwatch.Frequency * _times.Count / (time - _times.Peek()); var fpsString = ((int)(fps + 0.5)).ToString("D2"); terminal.Graphics.Print(color, fontSize, new Vector(GraphicsConstants.Width - fpsString.Length * fontSize, 0), fpsString); } if (_times.Count > 128) { _times.Dequeue(); } _times.Enqueue(time); } } } ```
69d3a5e8-8593-4fb5-802a-d93b1bd77e88
{ "language": "C#" }
```c# public static class AssemblyLine { private const int ProductionRatePerHourForDefaultSpeed = 221; public static double ProductionRatePerHour(int speed) => ProductionRatePerHourForSpeed(speed) * SuccessRate(speed); private static int ProductionRatePerHourForSpeed(int speed) => ProductionRatePerHourForDefaultSpeed * speed; public static int WorkingItemsPerMinute(int speed) => (int)ProductionRatePerHour(speed) / 60; private static double SuccessRate(int speed) { if (speed == 0) return 0.0; if (speed >= 9) return 0.77; if (speed < 5) return 1.0; return 0.9; } }``` Fix rounding error in numbers exercise
```c# public static class AssemblyLine { private const int ProductionRatePerHourForDefaultSpeed = 221; public static double ProductionRatePerHour(int speed) => ProductionRatePerHourForSpeed(speed) * SuccessRate(speed); private static int ProductionRatePerHourForSpeed(int speed) => ProductionRatePerHourForDefaultSpeed * speed; public static int WorkingItemsPerMinute(int speed) => (int)(ProductionRatePerHour(speed) / 60); private static double SuccessRate(int speed) { if (speed == 0) return 0.0; if (speed >= 9) return 0.77; if (speed < 5) return 1.0; return 0.9; } }```
9928ea38-77ba-4009-8e8d-6b37164de090
{ "language": "C#" }
```c# using System; using System.Net; namespace PackageExplorerViewModel.Types { public interface ICredentialManager { void TryAddUriCredentials(Uri feedUri); void Add(ICredentials credentials, Uri feedUri); ICredentials GetForUri(Uri uri); } } ``` Remove unused method from interface
```c# using System; using System.Net; namespace PackageExplorerViewModel.Types { public interface ICredentialManager { void Add(ICredentials credentials, Uri feedUri); ICredentials GetForUri(Uri uri); } } ```
976df02c-fb5b-43f8-85cd-c8058ec0c754
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Catch.Skinning.Default; using osu.Game.Rulesets.Objects.Pooling; using osu.Game.Skinning; namespace osu.Game.Rulesets.Catch.UI { public class HitExplosion : PoolableDrawableWithLifetime<HitExplosionEntry> { private SkinnableDrawable skinnableExplosion; public HitExplosion() { RelativeSizeAxes = Axes.Both; Anchor = Anchor.BottomCentre; Origin = Anchor.BottomCentre; } [BackgroundDependencyLoader] private void load() { InternalChild = skinnableExplosion = new SkinnableDrawable(new CatchSkinComponent(CatchSkinComponents.HitExplosion), _ => new DefaultHitExplosion()) { CentreComponent = false, Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre }; } protected override void OnApply(HitExplosionEntry entry) { base.OnApply(entry); ApplyTransformsAt(double.MinValue, true); ClearTransforms(true); (skinnableExplosion.Drawable as IHitExplosion)?.Animate(entry); LifetimeEnd = skinnableExplosion.Drawable.LatestTransformEndTime; } } } ``` Fix explosion reading out time values from wrong clock
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Catch.Skinning.Default; using osu.Game.Rulesets.Objects.Pooling; using osu.Game.Skinning; namespace osu.Game.Rulesets.Catch.UI { public class HitExplosion : PoolableDrawableWithLifetime<HitExplosionEntry> { private SkinnableDrawable skinnableExplosion; public HitExplosion() { RelativeSizeAxes = Axes.Both; Anchor = Anchor.BottomCentre; Origin = Anchor.BottomCentre; } [BackgroundDependencyLoader] private void load() { InternalChild = skinnableExplosion = new SkinnableDrawable(new CatchSkinComponent(CatchSkinComponents.HitExplosion), _ => new DefaultHitExplosion()) { CentreComponent = false, Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre }; } protected override void OnApply(HitExplosionEntry entry) { base.OnApply(entry); if (IsLoaded) apply(entry); } protected override void LoadComplete() { base.LoadComplete(); apply(Entry); } private void apply(HitExplosionEntry entry) { ApplyTransformsAt(double.MinValue, true); ClearTransforms(true); (skinnableExplosion.Drawable as IHitExplosion)?.Animate(entry); LifetimeEnd = skinnableExplosion.Drawable.LatestTransformEndTime; } } } ```
e5aa65b1-cd5c-4da8-8ba8-04bf476f737a
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Input.Bindings; using osu.Game.Database; using Realms; namespace osu.Game.Input.Bindings { [MapTo(nameof(KeyBinding))] public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding { [PrimaryKey] public Guid ID { get; set; } public int? RulesetID { get; set; } public int? Variant { get; set; } public KeyCombination KeyCombination { get => KeyCombinationString; set => KeyCombinationString = value.ToString(); } public object Action { get => ActionInt; set => ActionInt = (int)value; } [MapTo(nameof(Action))] public int ActionInt { get; set; } [MapTo(nameof(KeyCombination))] public string KeyCombinationString { get; set; } } } ``` Switch Guid implementation temporarily to avoid compile time error
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Input.Bindings; using osu.Game.Database; using Realms; namespace osu.Game.Input.Bindings { [MapTo(nameof(KeyBinding))] public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding { [PrimaryKey] public string StringGuid { get; set; } [Ignored] public Guid ID { get => Guid.Parse(StringGuid); set => StringGuid = value.ToString(); } public int? RulesetID { get; set; } public int? Variant { get; set; } public KeyCombination KeyCombination { get => KeyCombinationString; set => KeyCombinationString = value.ToString(); } public object Action { get => ActionInt; set => ActionInt = (int)value; } [MapTo(nameof(Action))] public int ActionInt { get; set; } [MapTo(nameof(KeyCombination))] public string KeyCombinationString { get; set; } } } ```
3e2e42d0-eafd-43fd-a357-c90876929318
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; using System; public class AnimateToPoint : MonoBehaviour { private SimpleTween tween; private Vector3 sourcePos; private Vector3 targetPos; private Action onComplete; private float timeScale; private float timer; public void Trigger(SimpleTween tween, Vector3 point) { Trigger(tween, point, () => {}); } public void Trigger(SimpleTween tween, Vector3 point, Action onComplete) { this.tween = tween; this.onComplete = onComplete; sourcePos = transform.position; targetPos = point; timeScale = 1.0f / tween.Duration; timer = 0.0f; } private void Update() { if (tween != null) { if (timer > 1.0f) { transform.position = targetPos; onComplete(); tween = null; } else { transform.position = tween.Evaluate(sourcePos, targetPos, timer); } timer += timeScale * Time.deltaTime; } } }``` Fix ordering bug when chaining Tweens
```c# using UnityEngine; using System.Collections; using System; public class AnimateToPoint : MonoBehaviour { private SimpleTween tween; private Vector3 sourcePos; private Vector3 targetPos; private Action onComplete; private float timeScale; private float timer; public void Trigger(SimpleTween tween, Vector3 point) { Trigger(tween, point, () => {}); } public void Trigger(SimpleTween tween, Vector3 point, Action onComplete) { this.tween = tween; this.onComplete = onComplete; sourcePos = transform.position; targetPos = point; timeScale = 1.0f / tween.Duration; timer = 0.0f; } private void Update() { if (tween != null) { if (timer > 1.0f) { tween = null; transform.position = targetPos; onComplete(); } else { transform.position = tween.Evaluate(sourcePos, targetPos, timer); } timer += timeScale * Time.deltaTime; } } }```
7d2f3b67-6d2d-4712-8270-42ac81189584
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class AdminModeMessageWindow : MonoBehaviour { private const float WINDOW_WIDTH = 300; private const float WINDOW_HEIGHT = 120; private const float MESSAGE_HEIGHT = 60; private const float BUTTON_HEIGHT = 30; private const float BUTTON_WIDTH = 40; private string Message; public void Initialize() { Message = "Could not sync player records to server.\nReason \"Player " + PlayerOptions.Name + " log corrupted\".\nAdmin mode enabled"; } void OnGUI () { GUI.Window(0, WindowRect, MessageWindow, "Error"); } void MessageWindow(int windowID) { GUI.Label(LabelRect, Message); if (GUI.Button(ButtonRect, "OK")) { enabled = false; } } private Rect WindowRect { get { var anchor = TransformToGuiFinder.Find(transform); return new Rect(anchor.x - WINDOW_WIDTH / 2, anchor.y - WINDOW_HEIGHT / 2, WINDOW_WIDTH, WINDOW_HEIGHT); } } private Rect LabelRect { get { return new Rect(10, 20, WINDOW_WIDTH, MESSAGE_HEIGHT); } } private Rect ButtonRect { get { return new Rect((WINDOW_WIDTH / 2) - (BUTTON_WIDTH / 2), 20 + MESSAGE_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); } } } ``` Change message to indicate player is freed from track
```c# using UnityEngine; using System.Collections; public class AdminModeMessageWindow : MonoBehaviour { private const float WINDOW_WIDTH = 300; private const float WINDOW_HEIGHT = 120; private const float MESSAGE_HEIGHT = 60; private const float BUTTON_HEIGHT = 30; private const float BUTTON_WIDTH = 40; private string Message; public void Initialize() { Message = "Could not sync player records to server.\nReason \"Player " + PlayerOptions.Name + " log corrupted\".\nAdmin mode enabled and player freed from track."; } void OnGUI () { GUI.Window(0, WindowRect, MessageWindow, "Error"); } void MessageWindow(int windowID) { GUI.Label(LabelRect, Message); if (GUI.Button(ButtonRect, "OK")) { enabled = false; } } private Rect WindowRect { get { var anchor = TransformToGuiFinder.Find(transform); return new Rect(anchor.x - WINDOW_WIDTH / 2, anchor.y - WINDOW_HEIGHT / 2, WINDOW_WIDTH, WINDOW_HEIGHT); } } private Rect LabelRect { get { return new Rect(10, 20, WINDOW_WIDTH, MESSAGE_HEIGHT); } } private Rect ButtonRect { get { return new Rect((WINDOW_WIDTH / 2) - (BUTTON_WIDTH / 2), 20 + MESSAGE_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); } } } ```
28f614f3-ed55-4d26-88b9-53a4f1a2c71b
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public interface IGetMetrics { IEnumerable<Metric> Deserialize(string response); } public class GetMetrics : IGetMetrics { public IEnumerable<Metric> Deserialize(string response) { var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response); return deserializeObject .Select(x => new Metric { Name = x.Key, Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(), WindowSize = x.Value.windowSize.ToObject<float>() }); } } }``` Handle optional version and fallback
```c# using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public interface IGetMetrics { IEnumerable<Metric> Deserialize(string response); } public class GetMetrics : IGetMetrics { public IEnumerable<Metric> Deserialize(string response) { var jObject = JObject.Parse(response); JToken versionToken; jObject.TryGetValue("version", out versionToken); var version = "0"; if (versionToken != null && versionToken.HasValues) { version = versionToken.Value<string>(); } if (version.Equals("0", StringComparison.OrdinalIgnoreCase)) { var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response); return deserializeObject .Select(x => new Metric { Name = x.Key, Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(), WindowSize = x.Value.windowSize.ToObject<float>() }); } return Enumerable.Empty<Metric>(); } } }```
2b1e14f3-d2db-4a96-a9f4-95b944ed7653
{ "language": "C#" }
```c# using System.Reactive.Linq; using System.Threading.Tasks; using NSubstitute; using Xunit; using UnitTests; using GitHub.Models; using System; using GitHub.Services; using GitHub.ViewModels; public class PullRequestCreationViewModelTests : TempFileBaseClass { [Fact] public async Task NullDescriptionBecomesEmptyBody() { var serviceProvider = Substitutes.ServiceProvider; var service = new PullRequestService(); var notifications = Substitute.For<INotificationService>(); var host = serviceProvider.GetRepositoryHosts().GitHubHost; var ms = Substitute.For<IModelService>(); host.ModelService.Returns(ms); var repository = new SimpleRepositoryModel("name", new GitHub.Primitives.UriString("http://github.com/github/stuff")); var title = "a title"; var vm = new PullRequestCreationViewModel(host, repository, service, notifications); vm.SourceBranch = new BranchModel() { Name = "source" }; vm.TargetBranch = new BranchModel() { Name = "target" }; vm.PRTitle = title; await vm.CreatePullRequest.ExecuteAsync(); ms.Received().CreatePullRequest(repository, vm.PRTitle, String.Empty, vm.SourceBranch, vm.TargetBranch); } } ``` Fix code warning in test
```c# using System.Reactive.Linq; using System.Threading.Tasks; using NSubstitute; using Xunit; using UnitTests; using GitHub.Models; using System; using GitHub.Services; using GitHub.ViewModels; public class PullRequestCreationViewModelTests : TempFileBaseClass { [Fact] public async Task NullDescriptionBecomesEmptyBody() { var serviceProvider = Substitutes.ServiceProvider; var service = new PullRequestService(); var notifications = Substitute.For<INotificationService>(); var host = serviceProvider.GetRepositoryHosts().GitHubHost; var ms = Substitute.For<IModelService>(); host.ModelService.Returns(ms); var repository = new SimpleRepositoryModel("name", new GitHub.Primitives.UriString("http://github.com/github/stuff")); var title = "a title"; var vm = new PullRequestCreationViewModel(host, repository, service, notifications); vm.SourceBranch = new BranchModel() { Name = "source" }; vm.TargetBranch = new BranchModel() { Name = "target" }; vm.PRTitle = title; await vm.CreatePullRequest.ExecuteAsync(); var unused = ms.Received().CreatePullRequest(repository, vm.PRTitle, String.Empty, vm.SourceBranch, vm.TargetBranch); } } ```
55c72fec-ca2f-4ffb-8163-6118f7499f1a
{ "language": "C#" }
```c# // ========================================================================== // SingleUrlsMiddleware.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Squidex.Pipeline { public sealed class SingleUrlsMiddleware { private readonly RequestDelegate next; private readonly ILogger<SingleUrlsMiddleware> logger; public SingleUrlsMiddleware(RequestDelegate next, ILoggerFactory factory) { this.next = next; logger = factory.CreateLogger<SingleUrlsMiddleware>(); } public async Task Invoke(HttpContext context) { var currentUrl = string.Concat(context.Request.Scheme, "://", context.Request.Host, context.Request.Path); var hostName = context.Request.Host.ToString().ToLowerInvariant(); if (hostName.StartsWith("www")) { hostName = hostName.Substring(3); } var requestPath = context.Request.Path.ToString(); if (!requestPath.EndsWith("/") && !requestPath.Contains(".")) { requestPath = requestPath + "/"; } var newUrl = string.Concat("https://", hostName, requestPath); if (!string.Equals(newUrl, currentUrl, StringComparison.OrdinalIgnoreCase)) { logger.LogError("Invalid url: {0} instead {1}", currentUrl, newUrl); context.Response.Redirect(newUrl, true); } else { await next(context); } } } } ``` Fix the query string stuff
```c# // ========================================================================== // SingleUrlsMiddleware.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Squidex.Pipeline { public sealed class SingleUrlsMiddleware { private readonly RequestDelegate next; private readonly ILogger<SingleUrlsMiddleware> logger; public SingleUrlsMiddleware(RequestDelegate next, ILoggerFactory factory) { this.next = next; logger = factory.CreateLogger<SingleUrlsMiddleware>(); } public async Task Invoke(HttpContext context) { var currentUrl = string.Concat(context.Request.Scheme, "://", context.Request.Host, context.Request.Path); var hostName = context.Request.Host.ToString().ToLowerInvariant(); if (hostName.StartsWith("www")) { hostName = hostName.Substring(3); } var requestPath = context.Request.Path.ToString(); if (!requestPath.EndsWith("/") && !requestPath.Contains(".")) { requestPath = requestPath + "/"; } var newUrl = string.Concat("https://", hostName, requestPath); if (!string.Equals(newUrl, currentUrl, StringComparison.OrdinalIgnoreCase)) { logger.LogError("Invalid url: {0} instead {1}", currentUrl, newUrl); context.Response.Redirect(newUrl + context.Request.QueryString, true); } else { await next(context); } } } } ```
94f73d13-0a75-4d5b-8667-ffc38059d368
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SceneJect.Common { public abstract class DepedencyInjectionFactoryService { /// <summary> /// Service for resolving dependencies. /// </summary> protected IResolver resolverService { get; } /// <summary> /// Strategy for injection. /// </summary> protected IInjectionStrategy injectionStrategy { get; } public DepedencyInjectionFactoryService(IResolver resolver, IInjectionStrategy injectionStrat) { if (resolver == null) throw new ArgumentNullException(nameof(resolver), $"Provided {nameof(IResolver)} service provided is null."); if (injectionStrategy == null) throw new ArgumentNullException(nameof(injectionStrategy), $"Provided {nameof(IInjectionStrategy)} service provided is null."); injectionStrategy = injectionStrat; resolverService = resolver; } } } ``` Fix Fault; Incorrect check in ctor
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SceneJect.Common { public abstract class DepedencyInjectionFactoryService { /// <summary> /// Service for resolving dependencies. /// </summary> protected IResolver resolverService { get; } /// <summary> /// Strategy for injection. /// </summary> protected IInjectionStrategy injectionStrategy { get; } public DepedencyInjectionFactoryService(IResolver resolver, IInjectionStrategy injectionStrat) { if (resolver == null) throw new ArgumentNullException(nameof(resolver), $"Provided {nameof(IResolver)} service provided is null."); if (injectionStrat == null) throw new ArgumentNullException(nameof(injectionStrat), $"Provided {nameof(IInjectionStrategy)} service provided is null."); injectionStrategy = injectionStrat; resolverService = resolver; } } } ```
c72abe90-4ba2-414e-8142-374517d7a98b
{ "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.Runtime.CompilerServices; using ObjCRuntime; // We publish our internal attributes to other sub-projects of the framework. // Note, that we omit visual tests as they are meant to test the framework // behavior "in the wild". [assembly: InternalsVisibleTo("osu.Framework.Tests")] [assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")] [assembly: LinkWith("libavcodec.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libavdevice.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libavfilter.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libavformat.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libavutil.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libbass.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libbass_fx.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libswresample.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libswscale.a", SmartLink = false, ForceLoad = true)] ``` Include BASSmix native library in linker
```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.Runtime.CompilerServices; using ObjCRuntime; // We publish our internal attributes to other sub-projects of the framework. // Note, that we omit visual tests as they are meant to test the framework // behavior "in the wild". [assembly: InternalsVisibleTo("osu.Framework.Tests")] [assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")] [assembly: LinkWith("libavcodec.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libavdevice.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libavfilter.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libavformat.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libavutil.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libbass.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libbass_fx.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libbassmix.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libswresample.a", SmartLink = false, ForceLoad = true)] [assembly: LinkWith("libswscale.a", SmartLink = false, ForceLoad = true)] ```
00f97b99-fa21-4bcb-8e60-c8a33246ea49
{ "language": "C#" }
```c# using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace WootzJs.Mvc { public class ControllerActionInvoker : IActionInvoker { public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action) { var parameters = action.GetParameters(); var args = new object[parameters.Length]; var lastParameter = parameters.LastOrDefault(); // If async if (lastParameter != null && lastParameter.ParameterType == typeof(Action<ActionResult>)) { return (Task<ActionResult>)action.Invoke(context.Controller, args); } // If synchronous else { var actionResult = (ActionResult)action.Invoke(context.Controller, args); return Task.FromResult(actionResult); } } } }``` Fix logic to use the new task based async pattern
```c# using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace WootzJs.Mvc { public class ControllerActionInvoker : IActionInvoker { public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action) { var parameters = action.GetParameters(); var args = new object[parameters.Length]; // If async if (action.ReturnType == typeof(Task<ActionResult>)) { return (Task<ActionResult>)action.Invoke(context.Controller, args); } // If synchronous else { var actionResult = (ActionResult)action.Invoke(context.Controller, args); return Task.FromResult(actionResult); } } } }```
7189e818-61a2-4a90-b52f-39ecba3afb09
{ "language": "C#" }
```c# using FluentScheduler; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; using System; namespace BatteryCommander.Web.Jobs { internal static class JobHandler { public static void WithScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger(typeof(JobHandler)); JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name); JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration); JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name); JobManager.UseUtcTime(); JobManager.JobFactory = new JobFactory(app.ApplicationServices); var registry = new Registry(); registry.Schedule<SqliteBackupJob>().ToRunNow().AndEvery(1).Days().At(hours: 12, minutes: 0); JobManager.Initialize(registry); } private class JobFactory : IJobFactory { private readonly IServiceProvider serviceProvider; public JobFactory(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } public IJob GetJobInstance<T>() where T : IJob { return serviceProvider.GetService(typeof(T)) as IJob; } } } }``` Fix registration to send nightly
```c# using FluentScheduler; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; using System; namespace BatteryCommander.Web.Jobs { internal static class JobHandler { public static void WithScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger(typeof(JobHandler)); JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name); JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration); JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name); JobManager.UseUtcTime(); JobManager.JobFactory = new JobFactory(app.ApplicationServices); var registry = new Registry(); registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 12, minutes: 0); JobManager.Initialize(registry); } private class JobFactory : IJobFactory { private readonly IServiceProvider serviceProvider; public JobFactory(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } public IJob GetJobInstance<T>() where T : IJob { return serviceProvider.GetService(typeof(T)) as IJob; } } } }```