doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
3f491634-4517-4cca-92d7-492f8b3b2720
{ "language": "C#" }
```c# // Copyright (c) Samuel Cragg. // // Licensed under the MIT license. See LICENSE file in the project root for // full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Samuel Cragg")] [assembly: AssemblyProduct("Crest.OpenApi")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("OpenApi.UnitTests")] ``` Allow substituting of internal types.
```c# // Copyright (c) Samuel Cragg. // // Licensed under the MIT license. See LICENSE file in the project root for // full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Samuel Cragg")] [assembly: AssemblyProduct("Crest.OpenApi")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // NSubstitute [assembly: InternalsVisibleTo("OpenApi.UnitTests")] ```
b5117578-ebba-44c9-b77d-8dbccce5bd76
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class DestroyEnemy : MonoBehaviour { public static int kills = 0; void OnCollisionEnter (Collision col) { if(col.gameObject.name.Contains("Monster")) { kills += 1; Destroy(col.gameObject); if (kills >= 5) { SceneManager.LoadScene ("GameWin", LoadSceneMode.Single); } } } }``` Reset the counter for the next playthrough - BH
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class DestroyEnemy : MonoBehaviour { public static int kills = 0; void OnCollisionEnter (Collision col) { if(col.gameObject.name.Contains("Monster")) { kills += 1; Destroy(col.gameObject); if (kills >= 5) { kills = 0; SceneManager.LoadScene ("GameWin", LoadSceneMode.Single); } } } }```
c922c2d5-6503-4c32-8403-70ac1353ae20
{ "language": "C#" }
```c# using System; using Microsoft.Extensions.DependencyInjection; using MR.Augmenter.Internal; namespace MR.Augmenter { public static class AugmenterServiceCollectionExtensions { public static IAugmenterBuilder AddAugmenter( this IServiceCollection services, Action<AugmenterConfiguration> configure) { services.AddScoped<IAugmenter, Augmenter>(); var configuration = new AugmenterConfiguration(); configure(configuration); configuration.Build(); services.AddSingleton(configuration); return new AugmenterBuilder(services); } } } ``` Allow configure to be null
```c# using System; using Microsoft.Extensions.DependencyInjection; using MR.Augmenter.Internal; namespace MR.Augmenter { public static class AugmenterServiceCollectionExtensions { /// <summary> /// Adds augmenter to services. /// </summary> /// <param name="services"></param> /// <param name="configure">Can be null.</param> public static IAugmenterBuilder AddAugmenter( this IServiceCollection services, Action<AugmenterConfiguration> configure) { services.AddScoped<IAugmenter, Augmenter>(); var configuration = new AugmenterConfiguration(); configure?.Invoke(configuration); configuration.Build(); services.AddSingleton(configuration); return new AugmenterBuilder(services); } } } ```
7df946f4-8857-4bf5-a03c-31d7b7c27f45
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Windows.Input; using AudioSharp.Utils; namespace AudioSharp.Config { public class ConfigHandler { public static void SaveConfig(Configuration config) { string json = JsonUtils.SerializeObject(config); File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json); } public static Configuration ReadConfig() { string path = Path.Combine(FileUtils.AppDataFolder, "settings.json"); if (File.Exists(path)) { string json = File.ReadAllText(path); Configuration config = JsonUtils.DeserializeObject<Configuration>(json); if (config.MP3EncodingPreset == 0) config.MP3EncodingPreset = 1001; return config; } return new Configuration() { RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), RecordingPrefix = "Recording{n}", NextRecordingNumber = 1, AutoIncrementRecordingNumber = true, OutputFormat = "wav", ShowTrayIcon = true, GlobalHotkeys = new Dictionary<HotkeyType, Tuple<Key, ModifierKeys>>(), RecordingSettingsPanelVisible = true, RecordingOutputPanelVisible = true, CheckForUpdates = true }; } } } ``` Set a default value for MP3 recording preset for new config files
```c# using System; using System.Collections.Generic; using System.IO; using System.Windows.Input; using AudioSharp.Utils; namespace AudioSharp.Config { public class ConfigHandler { public static void SaveConfig(Configuration config) { string json = JsonUtils.SerializeObject(config); File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json); } public static Configuration ReadConfig() { string path = Path.Combine(FileUtils.AppDataFolder, "settings.json"); if (File.Exists(path)) { string json = File.ReadAllText(path); Configuration config = JsonUtils.DeserializeObject<Configuration>(json); if (config.MP3EncodingPreset == 0) config.MP3EncodingPreset = 1001; return config; } return new Configuration() { RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), RecordingPrefix = "Recording{n}", NextRecordingNumber = 1, AutoIncrementRecordingNumber = true, OutputFormat = "wav", ShowTrayIcon = true, GlobalHotkeys = new Dictionary<HotkeyType, Tuple<Key, ModifierKeys>>(), RecordingSettingsPanelVisible = true, RecordingOutputPanelVisible = true, CheckForUpdates = true, MP3EncodingPreset = 1001 }; } } } ```
25ac93b6-6bae-45fc-825f-3f49f16b50aa
{ "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("ExtjsWd")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("ExtjsWd")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("efc31b18-7c2f-44f2-a1f3-4c49b28f409c")] // 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")] ``` Update assembly and file version
```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("ExtjsWd")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("ExtjsWd")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("efc31b18-7c2f-44f2-a1f3-4c49b28f409c")] // 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.2")] [assembly: AssemblyFileVersion("1.0.0.2")] ```
a562a879-d394-4e65-aabb-7a4673a2d0d9
{ "language": "C#" }
```c# using System.Linq; using BobTheBuilder.ArgumentStore.Queries; using JetBrains.Annotations; namespace BobTheBuilder.Activation { internal class InstanceCreator { private readonly IArgumentStoreQuery constructorArgumentsQuery; public InstanceCreator([NotNull]IArgumentStoreQuery constructorArgumentsQuery) { this.constructorArgumentsQuery = constructorArgumentsQuery; } public T CreateInstanceOf<T>() where T: class { var instanceType = typeof(T); var constructor = instanceType.GetConstructors().Single(); var constructorArguments = constructorArgumentsQuery.Execute(instanceType); return (T)constructor.Invoke(constructorArguments.Select(arg => arg.Value).ToArray()); } } } ``` Use safe cast for readability
```c# using System.Linq; using BobTheBuilder.ArgumentStore.Queries; using JetBrains.Annotations; namespace BobTheBuilder.Activation { internal class InstanceCreator { private readonly IArgumentStoreQuery constructorArgumentsQuery; public InstanceCreator([NotNull]IArgumentStoreQuery constructorArgumentsQuery) { this.constructorArgumentsQuery = constructorArgumentsQuery; } public T CreateInstanceOf<T>() where T: class { var instanceType = typeof(T); var constructor = instanceType.GetConstructors().Single(); var constructorArguments = constructorArgumentsQuery.Execute(instanceType); return constructor.Invoke(constructorArguments.Select(arg => arg.Value).ToArray()) as T; } } } ```
505349c1-96c5-42bc-a5b5-000a93938143
{ "language": "C#" }
```c# using System; using System.Web.Mvc; using TeacherPouch.Models; using TeacherPouch.Web.ViewModels; namespace TeacherPouch.Web.Controllers { public partial class PagesController : ControllerBase { // GET: / public virtual ViewResult Home() { return View(Views.Home); } public virtual ViewResult About() { return View(Views.About); } // GET: /Contact public virtual ViewResult Contact() { var viewModel = new ContactViewModel(); return View(Views.Contact, viewModel); } // POST: /Contact [HttpPost] [ValidateAntiForgeryToken] public virtual ActionResult Contact(ContactSubmission submision) { if (submision.IsValid) { if (!base.Request.IsLocal) { submision.SendEmail(); } } else { var viewModel = new ContactViewModel(); viewModel.ErrorMessage = "You must fill out the form before submitting."; return View(Views.Contact, viewModel); } return RedirectToAction(Actions.ContactThanks()); } // GET: /Contact/Thanks public virtual ViewResult ContactThanks() { return View(Views.ContactThanks); } // GET: /Copyright public virtual ViewResult Copyright() { return View(Views.Copyright); } } } ``` Change Copyright page to License page.
```c# using System; using System.Web.Mvc; using TeacherPouch.Models; using TeacherPouch.Web.ViewModels; namespace TeacherPouch.Web.Controllers { public partial class PagesController : ControllerBase { // GET: / public virtual ViewResult Home() { return View(Views.Home); } public virtual ViewResult About() { return View(Views.About); } // GET: /Contact public virtual ViewResult Contact() { var viewModel = new ContactViewModel(); return View(Views.Contact, viewModel); } // POST: /Contact [HttpPost] [ValidateAntiForgeryToken] public virtual ActionResult Contact(ContactSubmission submision) { if (submision.IsValid) { if (!base.Request.IsLocal) { submision.SendEmail(); } } else { var viewModel = new ContactViewModel(); viewModel.ErrorMessage = "You must fill out the form before submitting."; return View(Views.Contact, viewModel); } return RedirectToAction(Actions.ContactThanks()); } // GET: /Contact/Thanks public virtual ViewResult ContactThanks() { return View(Views.ContactThanks); } // GET: /License public virtual ViewResult License() { return View(Views.License); } } } ```
9146a7ba-3b6b-4f04-ba6e-acfb8e61befe
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation.Language; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions { // TODO Add documentation public static class Extensions { public static IEnumerable<string> GetLines(this string text) { return text.Split('\n').Select(line => line.TrimEnd('\r')); } public static IScriptExtent Translate(this IScriptExtent extent, int lineDelta, int columnDelta) { var newStartLineNumber = extent.StartLineNumber + lineDelta; if (newStartLineNumber < 1) { throw new ArgumentException( "Invalid line delta. Resulting start line number must be greather than 1."); } var newStartColumnNumber = extent.StartColumnNumber + columnDelta; var newEndColumnNumber = extent.EndColumnNumber + columnDelta; if (newStartColumnNumber < 1 || newEndColumnNumber < 1) { throw new ArgumentException(@"Invalid column delta. Resulting start column and end column number must be greather than 1."); } return new ScriptExtent( new ScriptPosition( extent.File, newStartLineNumber, newStartColumnNumber, extent.StartScriptPosition.Line), new ScriptPosition( extent.File, extent.EndLineNumber + lineDelta, newEndColumnNumber, extent.EndScriptPosition.Line)); } /// <summary> /// Converts IScriptExtent to Range /// </summary> public static Range ToRange(this IScriptExtent extent) { return new Range( extent.StartLineNumber, extent.StartColumnNumber, extent.EndLineNumber, extent.EndColumnNumber); } } } ``` Remove IScriptExtent.Translate method from extensions
```c# using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation.Language; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions { // TODO Add documentation public static class Extensions { public static IEnumerable<string> GetLines(this string text) { return text.Split('\n').Select(line => line.TrimEnd('\r')); } /// <summary> /// Converts IScriptExtent to Range /// </summary> public static Range ToRange(this IScriptExtent extent) { return new Range( extent.StartLineNumber, extent.StartColumnNumber, extent.EndLineNumber, extent.EndColumnNumber); } } } ```
67039100-fe33-4dbe-a7f8-2cb453a0a46c
{ "language": "C#" }
```c# using GitHub.Exports; using GitHub.UI; using GitHub.ViewModels; using System.ComponentModel.Composition; using System.Windows.Controls; using ReactiveUI; namespace GitHub.VisualStudio.UI.Views { public class GenericPullRequestCreationView : SimpleViewUserControl<IPullRequestCreationViewModel, GenericPullRequestCreationView> { } [ExportView(ViewType = UIViewType.PRCreation)] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class PullRequestCreationView : GenericPullRequestCreationView { public PullRequestCreationView() { InitializeComponent(); // DataContextChanged += (s, e) => ViewModel = e.NewValue as IPullRequestCreationViewModel; DataContextChanged += (s, e) => ViewModel = new GitHub.SampleData.PullRequestCreationViewModelDesigner() as IPullRequestCreationViewModel; this.WhenActivated(d => { }); } } } ``` Revert "Try to use SampleData instead of real data in the meantime"
```c# using GitHub.Exports; using GitHub.UI; using GitHub.ViewModels; using System.ComponentModel.Composition; using System.Windows.Controls; using ReactiveUI; namespace GitHub.VisualStudio.UI.Views { public class GenericPullRequestCreationView : SimpleViewUserControl<IPullRequestCreationViewModel, GenericPullRequestCreationView> { } [ExportView(ViewType = UIViewType.PRCreation)] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class PullRequestCreationView : GenericPullRequestCreationView { public PullRequestCreationView() { InitializeComponent(); DataContextChanged += (s, e) => ViewModel = e.NewValue as IPullRequestCreationViewModel; this.WhenActivated(d => { }); } } } ```
b43df912-8ccf-4933-bf77-fdf9e0678a74
{ "language": "C#" }
```c# using System.Linq; using System.Net; using AngleSharp; using AngleSharp.Parser.Html; namespace WebDriverManager.DriverConfigs.Impl { public class OperaConfig : IDriverConfig { public virtual string GetName() { return "Opera"; } public virtual string GetUrl32() { return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win32.zip"; } public virtual string GetUrl64() { return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win64.zip"; } public virtual string GetBinaryName() { return "operadriver.exe"; } public virtual string GetLatestVersion() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (var client = new WebClient()) { var htmlCode = client.DownloadString("https://github.com/operasoftware/operachromiumdriver/releases"); var parser = new HtmlParser(Configuration.Default.WithDefaultLoader()); var document = parser.Parse(htmlCode); var version = document.QuerySelectorAll("[class~='release-title'] a") .Select(element => element.TextContent) .FirstOrDefault(); return version; } } } }``` Simplify release title with version selector
```c# using System.Linq; using System.Net; using AngleSharp; using AngleSharp.Parser.Html; namespace WebDriverManager.DriverConfigs.Impl { public class OperaConfig : IDriverConfig { public virtual string GetName() { return "Opera"; } public virtual string GetUrl32() { return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win32.zip"; } public virtual string GetUrl64() { return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win64.zip"; } public virtual string GetBinaryName() { return "operadriver.exe"; } public virtual string GetLatestVersion() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (var client = new WebClient()) { var htmlCode = client.DownloadString("https://github.com/operasoftware/operachromiumdriver/releases"); var parser = new HtmlParser(Configuration.Default.WithDefaultLoader()); var document = parser.Parse(htmlCode); var version = document.QuerySelectorAll(".release-title > a") .Select(element => element.TextContent) .FirstOrDefault(); return version; } } } } ```
bb16d444-57b0-43bb-84c8-9069abceeada
{ "language": "C#" }
```c# namespace TraktApiSharp.Objects.Get.Shows.Seasons { using Newtonsoft.Json; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt season.</summary> public class TraktSeasonIds { /// <summary>Gets or sets the Trakt numeric id.</summary> [JsonProperty(PropertyName = "trakt")] public int Trakt { get; set; } /// <summary>Gets or sets the numeric id from thetvdb.com</summary> [JsonProperty(PropertyName = "tvdb")] public int? Tvdb { get; set; } /// <summary>Gets or sets the numeric id from themoviedb.org</summary> [JsonProperty(PropertyName = "tmdb")] public int? Tmdb { get; set; } /// <summary>Gets or sets the numeric id from tvrage.com</summary> [JsonProperty(PropertyName = "tvrage")] public int? TvRage { get; set; } /// <summary>Returns, whether any id has been set.</summary> [JsonIgnore] public bool HasAnyId => Trakt > 0 || Tvdb > 0 || Tvdb > 0 || TvRage > 0; } } ``` Add get best id method for season ids.
```c# namespace TraktApiSharp.Objects.Get.Shows.Seasons { using Newtonsoft.Json; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt season.</summary> public class TraktSeasonIds { /// <summary>Gets or sets the Trakt numeric id.</summary> [JsonProperty(PropertyName = "trakt")] public int Trakt { get; set; } /// <summary>Gets or sets the numeric id from thetvdb.com</summary> [JsonProperty(PropertyName = "tvdb")] public int? Tvdb { get; set; } /// <summary>Gets or sets the numeric id from themoviedb.org</summary> [JsonProperty(PropertyName = "tmdb")] public int? Tmdb { get; set; } /// <summary>Gets or sets the numeric id from tvrage.com</summary> [JsonProperty(PropertyName = "tvrage")] public int? TvRage { get; set; } /// <summary>Returns, whether any id has been set.</summary> [JsonIgnore] public bool HasAnyId => Trakt > 0 || Tvdb > 0 || Tvdb > 0 || TvRage > 0; /// <summary>Gets the most reliable id from those that have been set.</summary> /// <returns>The id as a string or an empty string, if no id is set.</returns> public string GetBestId() { if (Trakt > 0) return Trakt.ToString(); if (Tvdb.HasValue && Tvdb.Value > 0) return Tvdb.Value.ToString(); if (Tmdb.HasValue && Tmdb.Value > 0) return Tmdb.Value.ToString(); if (TvRage.HasValue && TvRage.Value > 0) return TvRage.Value.ToString(); return string.Empty; } } } ```
b822c693-824c-4fd8-bb3f-3cb9ee325cf2
{ "language": "C#" }
```c# using System; using System.Linq; using System.Web; using System.Web.Mvc; namespace Mindscape.Raygun4Net { public static class RaygunExceptionFilterAttacher { public static void AttachExceptionFilter(HttpApplication context, RaygunHttpModule module) { if (GlobalFilters.Filters.Count == 0) return; Filter filter = GlobalFilters.Filters.FirstOrDefault(f => f.Instance.GetType().FullName.Equals("System.Web.Mvc.HandleErrorAttribute")); if (filter != null) { GlobalFilters.Filters.Add(new RaygunExceptionFilterAttribute(context, module)); } } } } ``` Make sure the RaygunExceptionFilterAttribute hasn't already been added before we add it to the GlobalFilters list
```c# using System.Linq; using System.Web; using System.Web.Mvc; namespace Mindscape.Raygun4Net { public static class RaygunExceptionFilterAttacher { public static void AttachExceptionFilter(HttpApplication context, RaygunHttpModule module) { if (GlobalFilters.Filters.Count == 0) return; Filter filter = GlobalFilters.Filters.FirstOrDefault(f => f.Instance.GetType().FullName.Equals("System.Web.Mvc.HandleErrorAttribute")); if (filter != null) { if (GlobalFilters.Filters.Any(f => f.Instance.GetType() == typeof(RaygunExceptionFilterAttribute))) return; GlobalFilters.Filters.Add(new RaygunExceptionFilterAttribute(context, module)); } } } } ```
bbdf75b6-0314-4c0d-8557-04d34a4e8d02
{ "language": "C#" }
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace System.Web.OData.Design.Scaffolding { internal static class ScaffolderVersions { public static readonly Version WebApiODataScaffolderVersion = new Version(1, 0, 0, 0); } } ``` Fix Version Problem for Scaffolding
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace System.Web.OData.Design.Scaffolding { internal static class ScaffolderVersions { public static readonly Version WebApiODataScaffolderVersion = new Version(0, 1, 0, 0); } } ```
854ff966-94e7-4652-9603-0ed6a1d8f364
{ "language": "C#" }
```c# using System.Linq; using NUnit.Framework; namespace LastPass.Test { [TestFixture] class VaultTest { [Test] public void Create_returns_vault_with_correct_accounts() { var vault = Vault.Create(new Blob(TestData.Blob, 1)); Assert.AreEqual(TestData.Accounts.Length, vault.EncryptedAccounts.Length); Assert.AreEqual(TestData.Accounts.Select(i => i.Url), vault.EncryptedAccounts.Select(i => i.Url)); } [Test] public void DecryptAccount_decrypts_account() { var vault = Vault.Create(new Blob(TestData.Blob, 1)); var account = vault.DecryptAccount(vault.EncryptedAccounts[0], "p8utF7ZB8yD06SrtrD4hsdvEOiBU1Y19cr2dhG9DWZg=".Decode64()); Assert.AreEqual(TestData.Accounts[0].Name, account.Name); Assert.AreEqual(TestData.Accounts[0].Username, account.Username); Assert.AreEqual(TestData.Accounts[0].Password, account.Password); Assert.AreEqual(TestData.Accounts[0].Url, account.Url); } } } ``` Test that all accounts decrypt correctly
```c# using System.Linq; using NUnit.Framework; namespace LastPass.Test { [TestFixture] class VaultTest { [Test] public void Create_returns_vault_with_correct_accounts() { var vault = Vault.Create(new Blob(TestData.Blob, 1)); Assert.AreEqual(TestData.Accounts.Length, vault.EncryptedAccounts.Length); Assert.AreEqual(TestData.Accounts.Select(i => i.Url), vault.EncryptedAccounts.Select(i => i.Url)); } [Test] public void DecryptAccount_decrypts_accounts() { var vault = Vault.Create(new Blob(TestData.Blob, 1)); for (var i = 0; i < vault.EncryptedAccounts.Length; ++i) { var account = vault.DecryptAccount(vault.EncryptedAccounts[i], "p8utF7ZB8yD06SrtrD4hsdvEOiBU1Y19cr2dhG9DWZg=".Decode64()); var expectedAccount = TestData.Accounts[i]; Assert.AreEqual(expectedAccount.Name, account.Name); Assert.AreEqual(expectedAccount.Username, account.Username); Assert.AreEqual(expectedAccount.Password, account.Password); Assert.AreEqual(expectedAccount.Url, account.Url); } } } } ```
134cd3de-b539-4098-9f34-5a25acec16cb
{ "language": "C#" }
```c# using Urho.Gui; using Urho.Resources; namespace Urho.Portable { //TODO: generate this class using T4 from CoreData folder public static class CoreAssets { public static ResourceCache Cache => Application.Current.ResourceCache; public static class Models { public static Model Box => Cache.GetModel("Models/Box.mdl"); public static Model Cone => Cache.GetModel("Models/Cone.mdl"); public static Model Cylinder => Cache.GetModel("Models/Cylinder.mdl"); public static Model Plane => Cache.GetModel("Models/Plane.mdl"); public static Model Pyramid => Cache.GetModel("Models/Pyramid.mdl"); public static Model Sphere => Cache.GetModel("Models/Sphere.mdl"); public static Model Torus => Cache.GetModel("Models/Torus.mdl"); } public static class Materials { public static Material DefaultGrey => Cache.GetMaterial("Materials/DefaultGrey.xml"); } public static class Fonts { public static Font AnonymousPro => Cache.GetFont("Fonts/Anonymous Pro.ttf"); } public static class RenderPaths { } public static class Shaders { } public static class Techniques { } } } ``` Remove "Portable" from namespace name in CoreAssets
```c# using Urho.Gui; using Urho.Resources; namespace Urho { //TODO: generate this class using T4 from CoreData folder public static class CoreAssets { public static ResourceCache Cache => Application.Current.ResourceCache; public static class Models { public static Model Box => Cache.GetModel("Models/Box.mdl"); public static Model Cone => Cache.GetModel("Models/Cone.mdl"); public static Model Cylinder => Cache.GetModel("Models/Cylinder.mdl"); public static Model Plane => Cache.GetModel("Models/Plane.mdl"); public static Model Pyramid => Cache.GetModel("Models/Pyramid.mdl"); public static Model Sphere => Cache.GetModel("Models/Sphere.mdl"); public static Model Torus => Cache.GetModel("Models/Torus.mdl"); } public static class Materials { public static Material DefaultGrey => Cache.GetMaterial("Materials/DefaultGrey.xml"); } public static class Fonts { public static Font AnonymousPro => Cache.GetFont("Fonts/Anonymous Pro.ttf"); } public static class RenderPaths { } public static class Shaders { } public static class Techniques { } } } ```
ee02cce0-b2ac-49dd-9ed4-59c747e74f74
{ "language": "C#" }
```c# using System; using Microsoft.EntityFrameworkCore; using SupportManager.Telegram.DAL; using Topshelf; namespace SupportManager.Telegram { class Program { static void Main(string[] args) { if (args.Length == 2 && args[0].Equals("migrate", StringComparison.InvariantCultureIgnoreCase)) { var filename = args[1]; var builder = new DbContextOptionsBuilder<UserDbContext>(); builder.UseSqlite($"Data Source={filename}"); var db = new UserDbContext(builder.Options); db.Database.Migrate(); return; } var config = new Configuration(); var exitCode = HostFactory.Run(cfg => { cfg.AddCommandLineDefinition("db", v => config.DbFileName = v); cfg.AddCommandLineDefinition("botkey", v => config.BotKey = v); cfg.AddCommandLineDefinition("url", v => config.SupportManagerUri = new Uri(v)); cfg.AddCommandLineDefinition("hostUrl", v => config.HostUri = new Uri(v)); cfg.Service<Service>(svc => { svc.ConstructUsing(() => new Service(config)); svc.WhenStarted((s, h) => s.Start(h)); svc.WhenStopped((s, h) => s.Stop(h)); }); cfg.SetServiceName("SupportManager.Telegram"); cfg.SetDisplayName("SupportManager.Telegram"); cfg.SetDescription("SupportManager Telegram bot"); cfg.RunAsNetworkService(); cfg.StartAutomatically(); }); } } } ``` Replace main with top-level statements
```c# using System; using Microsoft.EntityFrameworkCore; using SupportManager.Telegram; using SupportManager.Telegram.Infrastructure; using Topshelf; if (args.Length == 2 && args[0].Equals("migrate", StringComparison.InvariantCultureIgnoreCase)) { var db = DbContextFactory.Create(args[1]); db.Database.Migrate(); return; } HostFactory.Run(cfg => { var config = new Configuration(); cfg.AddCommandLineDefinition("db", v => config.DbFileName = v); cfg.AddCommandLineDefinition("botkey", v => config.BotKey = v); cfg.AddCommandLineDefinition("url", v => config.SupportManagerUri = new Uri(v)); cfg.AddCommandLineDefinition("hostUrl", v => config.HostUri = new Uri(v)); cfg.Service<Service>(svc => { svc.ConstructUsing(() => new Service(config)); svc.WhenStarted((s, h) => s.Start(h)); svc.WhenStopped((s, h) => s.Stop(h)); }); cfg.SetServiceName("SupportManager.Telegram"); cfg.SetDisplayName("SupportManager.Telegram"); cfg.SetDescription("SupportManager Telegram bot"); cfg.RunAsNetworkService(); cfg.StartAutomatically(); });```
f29b45d1-012e-4899-8466-ee832fbe0d72
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace LazyStorage { public class StorableObject : IEquatable<StorableObject> { public int LazyStorageInternalId { get; set; } public Dictionary<string, string> Info { get; } public StorableObject() { Info = new Dictionary<string, string>(); } public bool Equals(StorableObject other) { return (other.LazyStorageInternalId == LazyStorageInternalId); } } }``` Remove Id from storable object
```c# using System; using System.Collections.Generic; namespace LazyStorage { public class StorableObject { public Dictionary<string, string> Info { get; } public StorableObject() { Info = new Dictionary<string, string>(); } } }```
b13c2766-328b-4673-a2dc-1f2f029950dd
{ "language": "C#" }
```c# using System; using System.Net; using System.Net.Http; using System.Web.Http; using Core.DomainModel; using Core.DomainServices; using Presentation.Web.Models; namespace Presentation.Web.Controllers.API { public class PasswordResetRequestController : BaseApiController { private readonly IUserService _userService; private readonly IUserRepository _userRepository; public PasswordResetRequestController(IUserService userService, IUserRepository userRepository) { _userService = userService; _userRepository = userRepository; } // POST api/PasswordResetRequest public HttpResponseMessage Post([FromBody] UserDTO input) { try { var user = _userRepository.GetByEmail(input.Email); var request = _userService.IssuePasswordReset(user, null, null); return Ok(); } catch (Exception e) { return CreateResponse(HttpStatusCode.InternalServerError, e); } } // GET api/PasswordResetRequest public HttpResponseMessage Get(string requestId) { try { var request = _userService.GetPasswordReset(requestId); if (request == null) return NotFound(); var dto = AutoMapper.Mapper.Map<PasswordResetRequest, PasswordResetRequestDTO>(request); var msg = CreateResponse(HttpStatusCode.OK, dto); return msg; } catch (Exception e) { return CreateResponse(HttpStatusCode.InternalServerError, e); } } } } ``` Allow anonymous on password reset requests
```c# using System; using System.Net; using System.Net.Http; using System.Web.Http; using Core.DomainModel; using Core.DomainServices; using Presentation.Web.Models; namespace Presentation.Web.Controllers.API { [AllowAnonymous] public class PasswordResetRequestController : BaseApiController { private readonly IUserService _userService; private readonly IUserRepository _userRepository; public PasswordResetRequestController(IUserService userService, IUserRepository userRepository) { _userService = userService; _userRepository = userRepository; } // POST api/PasswordResetRequest public HttpResponseMessage Post([FromBody] UserDTO input) { try { var user = _userRepository.GetByEmail(input.Email); var request = _userService.IssuePasswordReset(user, null, null); return Ok(); } catch (Exception e) { return CreateResponse(HttpStatusCode.InternalServerError, e); } } // GET api/PasswordResetRequest public HttpResponseMessage Get(string requestId) { try { var request = _userService.GetPasswordReset(requestId); if (request == null) return NotFound(); var dto = AutoMapper.Mapper.Map<PasswordResetRequest, PasswordResetRequestDTO>(request); var msg = CreateResponse(HttpStatusCode.OK, dto); return msg; } catch (Exception e) { return CreateResponse(HttpStatusCode.InternalServerError, e); } } } } ```
dbf2ca8b-12ac-47d1-9487-f0b79971394a
{ "language": "C#" }
```c# using System; using System.Web; using System.Web.Hosting; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } } ``` Use the AppSettings 'NuGetPackagePath' if exists and the default ~/Packages otherwise
```c# using System; using System.Web; using System.Web.Hosting; using System.Configuration; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath; private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); static PackageUtility() { string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"]; if (string.IsNullOrEmpty(packagePath)) { PackagePhysicalPath = DefaultPackagePhysicalPath; } else { PackagePhysicalPath = packagePath; } } public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } } ```
11c21e6d-146f-424a-85b4-3d6ed656e91a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace NFleet.Data { public class RouteEventData : IResponseData, IVersioned { public static string MIMEType = "application/vnd.jyu.nfleet.routeevent"; public static string MIMEVersion = "2.0"; int IVersioned.VersionNumber { get; set; } public string State { get; set; } public double WaitingTimeBefore { get; set; } public DateTime? ArrivalTime { get; set; } public DateTime? DepartureTime { get; set; } public List<Link> Meta { get; set; } public string DataState { get; set; } public string FeasibilityState { get; set; } public int TaskEventId { get; set; } public KPIData KPIs { get; set; } public string Type { get; set; } public LocationData Location { get; set; } } } ``` Add capacity and time window data to route events.
```c# using System; using System.Collections.Generic; namespace NFleet.Data { public class RouteEventData : IResponseData, IVersioned { public static string MIMEType = "application/vnd.jyu.nfleet.routeevent"; public static string MIMEVersion = "2.0"; int IVersioned.VersionNumber { get; set; } public string State { get; set; } public double WaitingTimeBefore { get; set; } public DateTime? ArrivalTime { get; set; } public DateTime? DepartureTime { get; set; } public List<Link> Meta { get; set; } public string DataState { get; set; } public string FeasibilityState { get; set; } public int TaskEventId { get; set; } public KPIData KPIs { get; set; } public string Type { get; set; } public LocationData Location { get; set; } public List<CapacityData> Capacities { get; set; } public List<TimeWindowData> TimeWindows { get; set; } } } ```
fbe33988-9e84-447b-98be-b979f0812c42
{ "language": "C#" }
```c# using System; using System.Linq; using System.Text; namespace SCPI { public class IDN : ICommand { public string Description => "Query the ID string of the instrument"; public string Manufacturer { get; private set; } public string Model { get; private set; } public string SerialNumber { get; private set; } public string SoftwareVersion { get; private set; } public string HelpMessage() { return nameof(IDN); } public string Command(params string[] parameters) { return "*IDN?"; } public bool Parse(byte[] data) { // RIGOL TECHNOLOGIES,<model>,<serial number>,<software version> var id = Encoding.ASCII.GetString(data).Split(',').Select(f => f.Trim()); // According to IEEE 488.2 there are four fields in the response if (id.Count() == 4) { Manufacturer = id.ElementAt(0); Model = id.ElementAt(1); SerialNumber = id.ElementAt(2); SoftwareVersion = id.ElementAt(3); return true; } return false; } } } ``` Change the method to expression body definition
```c# using System.Linq; using System.Text; namespace SCPI { public class IDN : ICommand { public string Description => "Query the ID string of the instrument"; public string Manufacturer { get; private set; } public string Model { get; private set; } public string SerialNumber { get; private set; } public string SoftwareVersion { get; private set; } public string HelpMessage() => nameof(IDN); public string Command(params string[] parameters) => "*IDN?"; public bool Parse(byte[] data) { // RIGOL TECHNOLOGIES,<model>,<serial number>,<software version> var id = Encoding.ASCII.GetString(data).Split(',').Select(f => f.Trim()); // According to IEEE 488.2 there are four fields in the response if (id.Count() == 4) { Manufacturer = id.ElementAt(0); Model = id.ElementAt(1); SerialNumber = id.ElementAt(2); SoftwareVersion = id.ElementAt(3); return true; } return false; } } } ```
96bd2a29-613b-49aa-ae5e-8bf0742f3c99
{ "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. namespace osu.Framework.Graphics.Cursor { /// <summary> /// Implementing this interface allows the implementing <see cref="Drawable"/> to display a custom tooltip if it is the child of a <see cref="TooltipContainer"/>. /// Keep in mind that tooltips can only be displayed by a <see cref="TooltipContainer"/> if the <see cref="Drawable"/> implementing <see cref="IHasCustomTooltip"/> has <see cref="Drawable.HandlePositionalInput"/> set to true. /// </summary> public interface IHasCustomTooltip : ITooltipContentProvider { /// <summary> /// The custom tooltip that should be displayed. /// </summary> /// <returns>The custom tooltip that should be displayed.</returns> ITooltip GetCustomTooltip(); /// <summary> /// Tooltip text that shows when hovering the drawable. /// </summary> object TooltipContent { get; } } /// <inheritdoc /> public interface IHasCustomTooltip<TContent> : IHasCustomTooltip { ITooltip IHasCustomTooltip.GetCustomTooltip() => GetCustomTooltip(); /// <inheritdoc cref="IHasCustomTooltip.GetCustomTooltip"/> new ITooltip<TContent> GetCustomTooltip(); object IHasCustomTooltip.TooltipContent => TooltipContent; /// <inheritdoc cref="IHasCustomTooltip.TooltipContent"/> new TContent TooltipContent { get; } } } ``` Add note about reusing of tooltips and the new behaviour
```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. namespace osu.Framework.Graphics.Cursor { /// <summary> /// Implementing this interface allows the implementing <see cref="Drawable"/> to display a custom tooltip if it is the child of a <see cref="TooltipContainer"/>. /// Keep in mind that tooltips can only be displayed by a <see cref="TooltipContainer"/> if the <see cref="Drawable"/> implementing <see cref="IHasCustomTooltip"/> has <see cref="Drawable.HandlePositionalInput"/> set to true. /// </summary> public interface IHasCustomTooltip : ITooltipContentProvider { /// <summary> /// The custom tooltip that should be displayed. /// </summary> /// <remarks> /// A tooltip may be reused between different drawables with different content if they share the same tooltip type. /// Therefore it is recommended for all displayed content in the tooltip to be provided by <see cref="TooltipContent"/> instead. /// </remarks> /// <returns>The custom tooltip that should be displayed.</returns> ITooltip GetCustomTooltip(); /// <summary> /// Tooltip text that shows when hovering the drawable. /// </summary> object TooltipContent { get; } } /// <inheritdoc /> public interface IHasCustomTooltip<TContent> : IHasCustomTooltip { ITooltip IHasCustomTooltip.GetCustomTooltip() => GetCustomTooltip(); /// <inheritdoc cref="IHasCustomTooltip.GetCustomTooltip"/> new ITooltip<TContent> GetCustomTooltip(); object IHasCustomTooltip.TooltipContent => TooltipContent; /// <inheritdoc cref="IHasCustomTooltip.TooltipContent"/> new TContent TooltipContent { get; } } } ```
b624ca7b-38d8-41ec-92a0-3efcaa594c77
{ "language": "C#" }
```c# using NPoco; using System; namespace Dalian.Models { [PrimaryKey("SiteId")] public class Sites { public string SiteId { get; set; } public string Name { get; set; } public string Url { get; set; } public string Note { get; set; } public string Source { get; set; } public DateTime DateTime { get; set; } public bool Active { get; set; } public string MetaTitle { get; set; } public string MetaDescription { get; set; } public string MetaKeywords { get; set; } public int Status { get; set; } public bool Bookmarklet { get; set; } public bool ReadItLater { get; set; } public bool Clipped { get; set; } public string ArchiveUrl { get; set; } public bool Highlight { get; set; } public bool PersonalHighlight { get; set; } } }``` Fix not null constraint failed exception
```c# using NPoco; using System; namespace Dalian.Models { [PrimaryKey("SiteId", AutoIncrement = false)] public class Sites { public string SiteId { get; set; } public string Name { get; set; } public string Url { get; set; } public string Note { get; set; } public string Source { get; set; } public DateTime DateTime { get; set; } public bool Active { get; set; } public string MetaTitle { get; set; } public string MetaDescription { get; set; } public string MetaKeywords { get; set; } public int Status { get; set; } public bool Bookmarklet { get; set; } public bool ReadItLater { get; set; } public bool Clipped { get; set; } public string ArchiveUrl { get; set; } public bool Highlight { get; set; } public bool PersonalHighlight { get; set; } } }```
f2f09e69-bb7f-4562-a8e0-ece17216b489
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Autofac; using Autofac.Core; namespace ServiceStack.DependencyInjection { public class DependencyResolver : IDisposable { private readonly ILifetimeScope _lifetimeScope; public DependencyResolver(ILifetimeScope lifetimeScope) { _lifetimeScope = lifetimeScope; } public T Resolve<T>() { return _lifetimeScope.Resolve<T>(); } public object Resolve(Type type) { return _lifetimeScope.Resolve(type); } public T TryResolve<T>() { try { return _lifetimeScope.Resolve<T>(); } catch (DependencyResolutionException unusedException) { return default(T); } } public void Dispose() { _lifetimeScope.Dispose(); } } } ``` Check if registered before trying.
```c# using System; using System.Collections.Generic; using Autofac; using Autofac.Core; namespace ServiceStack.DependencyInjection { public class DependencyResolver : IDisposable { private readonly ILifetimeScope _lifetimeScope; public DependencyResolver(ILifetimeScope lifetimeScope) { _lifetimeScope = lifetimeScope; } public T Resolve<T>() { return _lifetimeScope.Resolve<T>(); } public object Resolve(Type type) { return _lifetimeScope.Resolve(type); } public T TryResolve<T>() { if (_lifetimeScope.IsRegistered<T>()) { try { return _lifetimeScope.Resolve<T>(); } catch (DependencyResolutionException unusedException) { return default(T); } } else { return default (T); } } public void Dispose() { _lifetimeScope.Dispose(); } } } ```
5d88623e-c3ea-45e8-8f62-7f6e302a588c
{ "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.Events; using osu.Framework.Utils; using osu.Game.Graphics.Containers; namespace osu.Game.Beatmaps.Drawables.Cards { public class ExpandedContentScrollContainer : OsuScrollContainer { public const float HEIGHT = 400; public ExpandedContentScrollContainer() { ScrollbarVisible = false; } protected override void Update() { base.Update(); Height = Math.Min(Content.DrawHeight, HEIGHT); } private bool allowScroll => !Precision.AlmostEquals(DrawSize, Content.DrawSize); protected override bool OnDragStart(DragStartEvent e) { if (!allowScroll) return false; return base.OnDragStart(e); } protected override void OnDrag(DragEvent e) { if (!allowScroll) return; base.OnDrag(e); } protected override void OnDragEnd(DragEndEvent e) { if (!allowScroll) return; base.OnDragEnd(e); } protected override bool OnScroll(ScrollEvent e) { if (!allowScroll) return false; return base.OnScroll(e); } } } ``` Change expanded card content height to 200
```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.Events; using osu.Framework.Utils; using osu.Game.Graphics.Containers; namespace osu.Game.Beatmaps.Drawables.Cards { public class ExpandedContentScrollContainer : OsuScrollContainer { public const float HEIGHT = 200; public ExpandedContentScrollContainer() { ScrollbarVisible = false; } protected override void Update() { base.Update(); Height = Math.Min(Content.DrawHeight, HEIGHT); } private bool allowScroll => !Precision.AlmostEquals(DrawSize, Content.DrawSize); protected override bool OnDragStart(DragStartEvent e) { if (!allowScroll) return false; return base.OnDragStart(e); } protected override void OnDrag(DragEvent e) { if (!allowScroll) return; base.OnDrag(e); } protected override void OnDragEnd(DragEndEvent e) { if (!allowScroll) return; base.OnDragEnd(e); } protected override bool OnScroll(ScrollEvent e) { if (!allowScroll) return false; return base.OnScroll(e); } } } ```
63a2fc6b-5a03-490a-96b6-6d72a5620686
{ "language": "C#" }
```c# @model dynamic @{ ViewBag.Title = "Регистрация успешна"; } <h2>@ViewBag.Title</h2> <p>Остался всего один клик! Проверьте свою почту, там лежит письмо от нас с просьбой подтвердить email...</p> ``` Change message in register success
```c# @model dynamic @{ ViewBag.Title = "Регистрация успешна"; } <h2>@ViewBag.Title</h2> <p>Остался всего один клик! Проверьте свою почту, там лежит письмо от нас с просьбой подтвердить email.</p> ```
cff90967-3510-4475-a869-9bd416b19602
{ "language": "C#" }
```c# using System; using Ooui; namespace Samples { class Program { static void Main (string[] args) { new ButtonSample ().Publish (); new TodoSample ().Publish (); Console.ReadLine (); } } } ``` Add --port option to samples
```c# using System; using Ooui; namespace Samples { class Program { static void Main (string[] args) { for (var i = 0; i < args.Length; i++) { var a = args[i]; switch (args[i]) { case "-p" when i + 1 < args.Length: case "--port" when i + 1 < args.Length: { int p; if (int.TryParse (args[i + 1], out p)) { UI.Port = p; } i++; } break; } } new ButtonSample ().Publish (); new TodoSample ().Publish (); Console.ReadLine (); } } } ```
fe6bd2f4-5c09-43ef-9ff4-beee9d10056d
{ "language": "C#" }
```c# using Hangfire.Common; using Hangfire.Console.Serialization; using Hangfire.Console.Storage; using Hangfire.Server; using Hangfire.States; using System; namespace Hangfire.Console.Server { /// <summary> /// Server filter to initialize and cleanup console environment. /// </summary> internal class ConsoleServerFilter : IServerFilter { private readonly ConsoleOptions _options; public ConsoleServerFilter(ConsoleOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); _options = options; } public void OnPerforming(PerformingContext context) { var state = context.Connection.GetStateData(context.BackgroundJob.Id); if (state == null) { // State for job not found? return; } if (!string.Equals(state.Name, ProcessingState.StateName, StringComparison.OrdinalIgnoreCase)) { // Not in Processing state? Something is really off... return; } var startedAt = JobHelper.DeserializeDateTime(state.Data["StartedAt"]); context.Items["ConsoleContext"] = new ConsoleContext( new ConsoleId(context.BackgroundJob.Id, startedAt), new ConsoleStorage(context.Connection)); } public void OnPerformed(PerformedContext context) { if (context.Canceled) { // Processing was been cancelled by one of the job filters // There's nothing to do here, as processing hasn't started return; } ConsoleContext.FromPerformContext(context)?.Expire(_options.ExpireIn); } } } ``` Rename arguments to match base names
```c# using Hangfire.Common; using Hangfire.Console.Serialization; using Hangfire.Console.Storage; using Hangfire.Server; using Hangfire.States; using System; namespace Hangfire.Console.Server { /// <summary> /// Server filter to initialize and cleanup console environment. /// </summary> internal class ConsoleServerFilter : IServerFilter { private readonly ConsoleOptions _options; public ConsoleServerFilter(ConsoleOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); _options = options; } public void OnPerforming(PerformingContext filterContext) { var state = filterContext.Connection.GetStateData(filterContext.BackgroundJob.Id); if (state == null) { // State for job not found? return; } if (!string.Equals(state.Name, ProcessingState.StateName, StringComparison.OrdinalIgnoreCase)) { // Not in Processing state? Something is really off... return; } var startedAt = JobHelper.DeserializeDateTime(state.Data["StartedAt"]); filterContext.Items["ConsoleContext"] = new ConsoleContext( new ConsoleId(filterContext.BackgroundJob.Id, startedAt), new ConsoleStorage(filterContext.Connection)); } public void OnPerformed(PerformedContext filterContext) { if (filterContext.Canceled) { // Processing was been cancelled by one of the job filters // There's nothing to do here, as processing hasn't started return; } ConsoleContext.FromPerformContext(filterContext)?.Expire(_options.ExpireIn); } } } ```
c864b376-36ab-4210-94c7-df54eee609da
{ "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.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModTouchDevice : Mod { public override string Name => "Touch Device"; public override string Acronym => "TD"; public override double ScoreMultiplier => 1; } } ``` Fix TD mod not being ranked
```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.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModTouchDevice : Mod { public override string Name => "Touch Device"; public override string Acronym => "TD"; public override double ScoreMultiplier => 1; public override bool Ranked => true; } } ```
df168a65-6e81-4d9f-8234-7735996a2f5f
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; public class DarkRoomObstacleEnable : MonoBehaviour { [SerializeField] private float maxXDistance = 11f; void Start () { } void Update () { for (int i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); var shouldEnable = Mathf.Abs(MainCameraSingleton.instance.transform.position.x - child.position.x) <= maxXDistance; if (shouldEnable != child.gameObject.activeInHierarchy) child.gameObject.SetActive(shouldEnable); } } } ``` Destroy obstacles disabled at scene start
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class DarkRoomObstacleEnable : MonoBehaviour { [SerializeField] private float maxXDistance = 11f; void Start () { for (int i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); if (!child.gameObject.activeInHierarchy) Destroy(child.gameObject); } } void Update () { for (int i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); var shouldEnable = Mathf.Abs(MainCameraSingleton.instance.transform.position.x - child.position.x) <= maxXDistance; if (shouldEnable != child.gameObject.activeInHierarchy) child.gameObject.SetActive(shouldEnable); } } } ```
49c6e682-5b3f-4954-a177-6eb13451bff5
{ "language": "C#" }
```c# using System; namespace clipr { /// <summary> /// Mark the property as a subcommand. (cf. 'svn checkout') /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public class VerbAttribute : Attribute { /// <summary> /// Name of the subcommand. If provided as an argument, it /// will trigger parsing of the subcommand. /// </summary> public string Name { get; private set; } /// <summary> /// Description of the subcommand, suitable for help pages. /// </summary> public string Description { get; private set; } /// <summary> /// Create a new subcommand. /// </summary> /// <param name="name"></param> public VerbAttribute(string name) { Name = name; } /// <summary> /// Create a new subcommand. /// </summary> /// <param name="name"></param> /// <param name="description"></param> public VerbAttribute(string name, string description) { Name = name; Description = description; } } } ``` Allow verb name to be optional.
```c# using System; namespace clipr { /// <summary> /// Mark the property as a subcommand. (cf. 'svn checkout') /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public class VerbAttribute : Attribute { /// <summary> /// Name of the subcommand. If provided as an argument, it /// will trigger parsing of the subcommand. /// </summary> public string Name { get; set; } /// <summary> /// Description of the subcommand, suitable for help pages. /// </summary> public string Description { get; set; } /// <summary> /// Create a new subcommand. /// </summary> public VerbAttribute() { } /// <summary> /// Create a new subcommand. /// </summary> /// <param name="name"></param> public VerbAttribute(string name) { Name = name; } /// <summary> /// Create a new subcommand. /// </summary> /// <param name="name"></param> /// <param name="description"></param> public VerbAttribute(string name, string description) { Name = name; Description = description; } } } ```
4cb37f64-25a4-40e8-8d4d-d3909b501929
{ "language": "C#" }
```c# #tool nuget:?package=XamarinComponent&version=1.1.0.32 #addin nuget:?package=Cake.Xamarin.Build&version=1.0.14.0 #addin nuget:?package=Cake.Xamarin #addin nuget:?package=Cake.XCode ``` Remove explicit build addin dependency version
```c# #tool nuget:?package=XamarinComponent&version=1.1.0.32 #addin nuget:?package=Cake.Xamarin.Build #addin nuget:?package=Cake.Xamarin #addin nuget:?package=Cake.XCode ```
2749ddec-8392-4506-856f-248abab67455
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using KafkaNet; using KafkaNet.Model; using KafkaNet.Protocol; using System.Collections.Generic; namespace TestHarness { class Program { static void Main(string[] args) { var options = new KafkaOptions(new Uri("http://CSDKAFKA01:9092"), new Uri("http://CSDKAFKA02:9092")) { Log = new ConsoleLog() }; var router = new BrokerRouter(options); var client = new Producer(router); Task.Factory.StartNew(() => { var consumer = new Consumer(new ConsumerOptions("TestHarness", router)); foreach (var data in consumer.Consume()) { Console.WriteLine("Response: P{0},O{1} : {2}", data.Meta.PartitionId, data.Meta.Offset, data.Value); } }); Console.WriteLine("Type a message and press enter..."); while (true) { var message = Console.ReadLine(); if (message == "quit") break; client.SendMessageAsync("TestHarness", new[] { new Message(message) }); } using (client) using (router) { } } } } ``` Clean up TestHarness to be more instructive
```c# using System; using System.Threading.Tasks; using KafkaNet; using KafkaNet.Common; using KafkaNet.Model; using KafkaNet.Protocol; using System.Collections.Generic; namespace TestHarness { class Program { static void Main(string[] args) { //create an options file that sets up driver preferences var options = new KafkaOptions(new Uri("http://CSDKAFKA01:9092"), new Uri("http://CSDKAFKA02:9092")) { Log = new ConsoleLog() }; //start an out of process thread that runs a consumer that will write all received messages to the console Task.Factory.StartNew(() => { var consumer = new Consumer(new ConsumerOptions("TestHarness", new BrokerRouter(options))); foreach (var data in consumer.Consume()) { Console.WriteLine("Response: P{0},O{1} : {2}", data.Meta.PartitionId, data.Meta.Offset, data.Value.ToUTF8String()); } }); //create a producer to send messages with var producer = new Producer(new BrokerRouter(options)); Console.WriteLine("Type a message and press enter..."); while (true) { var message = Console.ReadLine(); if (message == "quit") break; if (string.IsNullOrEmpty(message)) { //special case, send multi messages quickly for (int i = 0; i < 20; i++) { producer.SendMessageAsync("TestHarness", new[] { new Message(i.ToString()) }) .ContinueWith(t => { t.Result.ForEach(x => Console.WriteLine("Complete: {0}, Offset: {1}", x.PartitionId, x.Offset)); }); } } else { producer.SendMessageAsync("TestHarness", new[] { new Message(message) }); } } using (producer) { } } } } ```
65e0b65d-ccbf-4e54-90c3-33fba6061ad9
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace TweetDuck.Video.Controls{ sealed class LabelTooltip : Label{ public LabelTooltip(){ Visible = false; } public void AttachTooltip(Control control, bool followCursor, string tooltip){ AttachTooltip(control, followCursor, args => tooltip); } public void AttachTooltip(Control control, bool followCursor, Func<MouseEventArgs, string> tooltipFunc){ control.MouseEnter += control_MouseEnter; control.MouseLeave += control_MouseLeave; control.MouseMove += (sender, args) => { Form form = control.FindForm(); Debug.Assert(form != null); Text = tooltipFunc(args); Location = form.PointToClient(control.Parent.PointToScreen(new Point(control.Location.X-Width/2+(followCursor ? args.X : control.Width/2), -Height+Margin.Top-Margin.Bottom)));; }; } private void control_MouseEnter(object sender, EventArgs e){ Visible = true; } private void control_MouseLeave(object sender, EventArgs e){ Visible = false; } } } ``` Fix video player tooltip going outside Form bounds
```c# using System; using System.Drawing; using System.Windows.Forms; namespace TweetDuck.Video.Controls{ sealed class LabelTooltip : Label{ public LabelTooltip(){ Visible = false; } public void AttachTooltip(Control control, bool followCursor, string tooltip){ AttachTooltip(control, followCursor, args => tooltip); } public void AttachTooltip(Control control, bool followCursor, Func<MouseEventArgs, string> tooltipFunc){ control.MouseEnter += control_MouseEnter; control.MouseLeave += control_MouseLeave; control.MouseMove += (sender, args) => { Form form = control.FindForm(); System.Diagnostics.Debug.Assert(form != null); Text = tooltipFunc(args); Point loc = form.PointToClient(control.Parent.PointToScreen(new Point(control.Location.X+(followCursor ? args.X : control.Width/2), 0))); loc.X = Math.Max(0, Math.Min(form.Width-Width, loc.X-Width/2)); loc.Y -= Height-Margin.Top+Margin.Bottom; Location = loc; }; } private void control_MouseEnter(object sender, EventArgs e){ Visible = true; } private void control_MouseLeave(object sender, EventArgs e){ Visible = false; } } } ```
a79e2588-177d-499a-8a32-066f6e7c3c3b
{ "language": "C#" }
```c# // Licensed under the GPL License, Version 3.0. See LICENSE in the git repository root for license information. using Newtonsoft.Json; namespace Ecwid.Models { /// <summary> /// </summary> public class TaxRule { /// <summary> /// Gets or sets the tax in %. /// </summary> /// <value> /// The tax. /// </value> [JsonProperty("tax")] public int Tax { get; set; } /// <summary> /// Gets or sets the destination zone identifier. /// </summary> /// <value> /// The zone identifier. /// </value> [JsonProperty("zoneId")] public string ZoneId { get; set; } } }``` Fix tax rule to be double not int
```c# // Licensed under the GPL License, Version 3.0. See LICENSE in the git repository root for license information. using Newtonsoft.Json; namespace Ecwid.Models { /// <summary> /// </summary> public class TaxRule { /// <summary> /// Gets or sets the tax in %. /// </summary> /// <value> /// The tax. /// </value> [JsonProperty("tax")] public double Tax { get; set; } /// <summary> /// Gets or sets the destination zone identifier. /// </summary> /// <value> /// The zone identifier. /// </value> [JsonProperty("zoneId")] public string ZoneId { get; set; } } }```
5bf5f018-084a-487a-a5cf-6b363f725f31
{ "language": "C#" }
```c# using System; using System.Data; using System.Data.Common; namespace Rebus.AdoNet.Dialects { public class PostgreSql82Dialect : PostgreSqlDialect { protected override Version MinimumDatabaseVersion => new Version("8.2"); public override ushort Priority => 82; public override bool SupportsReturningClause => true; public override bool SupportsSelectForWithNoWait => true; public override string SelectForNoWaitClause => "NOWAIT"; public override bool IsSelectForNoWaitLockingException(DbException ex) { if (ex != null && ex.GetType().Name == "NpgsqlException") { var psqlex = new PostgreSqlExceptionAdapter(ex); return psqlex.Code == "55P03"; } return false; } } } ``` Add PostgresException on postgresExceptionNames fixing select for NoWait locking exceptions
```c# using System; using System.Linq; using System.Collections.Generic; using System.Data; using System.Data.Common; namespace Rebus.AdoNet.Dialects { public class PostgreSql82Dialect : PostgreSqlDialect { private static readonly IEnumerable<string> _postgresExceptionNames = new[] { "NpgsqlException", "PostgresException" }; protected override Version MinimumDatabaseVersion => new Version("8.2"); public override ushort Priority => 82; public override bool SupportsReturningClause => true; public override bool SupportsSelectForWithNoWait => true; public override string SelectForNoWaitClause => "NOWAIT"; public override bool IsSelectForNoWaitLockingException(DbException ex) { if (ex != null && _postgresExceptionNames.Contains(ex.GetType().Name)) { var psqlex = new PostgreSqlExceptionAdapter(ex); return psqlex.Code == "55P03"; } return false; } } } ```
8ca55919-6ff9-4af2-9c67-1f5d22bb7657
{ "language": "C#" }
```c# using UnityEditor; using UnityEngine; namespace Tactosy.Unity { [CustomEditor(typeof(Manager_Tactosy))] public class TactosyEditor : Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); Manager_Tactosy tactosyManager = (Manager_Tactosy) target; foreach (var mappings in tactosyManager.FeedbackMappings) { var key = mappings.Key; if (GUILayout.Button(key)) { tactosyManager.Play(key); } } if (GUILayout.Button("Turn Off")) { tactosyManager.TurnOff(); } } } } ``` Add preprocessor to prevent compilation error
```c# #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; namespace Tactosy.Unity { #if UNITY_EDITOR [CustomEditor(typeof(Manager_Tactosy))] public class TactosyEditor : Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); Manager_Tactosy tactosyManager = (Manager_Tactosy) target; foreach (var mappings in tactosyManager.FeedbackMappings) { var key = mappings.Key; if (GUILayout.Button(key)) { tactosyManager.Play(key); } } if (GUILayout.Button("Turn Off")) { tactosyManager.TurnOff(); } } } #endif } ```
6af94d6b-67b0-44aa-8c9f-d767565b52fc
{ "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 Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class SignatureHelpRequest { public static readonly RequestType<TextDocumentPositionParams, SignatureHelp, object, object> Type = RequestType<TextDocumentPositionParams, SignatureHelp, object, object>.Create("textDocument/signatureHelp"); } public class ParameterInformation { public string Label { get; set; } public string Documentation { get; set; } } public class SignatureInformation { public string Label { get; set; } public string Documentation { get; set; } public ParameterInformation[] Parameters { get; set; } } public class SignatureHelp { public SignatureInformation[] Signatures { get; set; } public int? ActiveSignature { get; set; } public int? ActiveParameter { get; set; } } } ``` Add registration options for signaturehelp request
```c# // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class SignatureHelpRequest { public static readonly RequestType<TextDocumentPositionParams, SignatureHelp, object, SignatureHelpRegistrationOptions> Type = RequestType<TextDocumentPositionParams, SignatureHelp, object, SignatureHelpRegistrationOptions>.Create("textDocument/signatureHelp"); } public class SignatureHelpRegistrationOptions : TextDocumentRegistrationOptions { // We duplicate the properties of SignatureHelpOptions class here because // we cannot derive from two classes. One way to get around this situation // is to use define SignatureHelpOptions as an interface instead of a class. public string[] TriggerCharacters { get; set; } } public class ParameterInformation { public string Label { get; set; } public string Documentation { get; set; } } public class SignatureInformation { public string Label { get; set; } public string Documentation { get; set; } public ParameterInformation[] Parameters { get; set; } } public class SignatureHelp { public SignatureInformation[] Signatures { get; set; } public int? ActiveSignature { get; set; } public int? ActiveParameter { get; set; } } } ```
fb29642d-bd11-4a08-a978-2d58854ca09c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Biggy.SqlCe.Tests { [Trait("SQL CE Compact column mapping", "")] public class SqlCEColumnMapping { public string _connectionStringName = "chinook"; [Fact(DisplayName = "Maps Pk if specified by attribute")] public void MapingSpecifiedPk() { var db = new SqlCeStore<Album>(_connectionStringName); //, "Album" var pkMap = db.TableMapping.PrimaryKeyMapping; Assert.Single(pkMap); Assert.Equal("Id", pkMap[0].PropertyName); Assert.Equal("AlbumId", pkMap[0].ColumnName); Assert.True(pkMap[0].IsAutoIncementing); } [Fact(DisplayName = "Maps Pk even if wasn't specified by attribute")] public void MapingNotSpecifiedPk() { var db = new SqlCeStore<Genre>(_connectionStringName); //, "Genre" var pkMap = db.TableMapping.PrimaryKeyMapping; Assert.Single(pkMap); Assert.Equal("Id", pkMap[0].PropertyName); Assert.Equal("GenreId", pkMap[0].ColumnName); Assert.True(pkMap[0].IsAutoIncementing); } } } ``` Add another mapping test, non-auto inc Pk
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Biggy.SqlCe.Tests { [Trait("SQL CE Compact column mapping", "")] public class SqlCEColumnMapping { public string _connectionStringName = "chinook"; [Fact(DisplayName = "Maps Pk if specified by attribute")] public void MapingSpecifiedPk() { var db = new SqlCeStore<Album>(_connectionStringName); //, "Album" var pkMap = db.TableMapping.PrimaryKeyMapping; Assert.Single(pkMap); Assert.Equal("Id", pkMap[0].PropertyName); Assert.Equal("AlbumId", pkMap[0].ColumnName); Assert.True(pkMap[0].IsAutoIncementing); } [Fact(DisplayName = "Maps Pk even if wasn't specified by attribute")] public void MapingNotSpecifiedPk() { var db = new SqlCeStore<Genre>(_connectionStringName); //, "Genre" var pkMap = db.TableMapping.PrimaryKeyMapping; Assert.Single(pkMap); Assert.Equal("Id", pkMap[0].PropertyName); Assert.Equal("GenreId", pkMap[0].ColumnName); Assert.True(pkMap[0].IsAutoIncementing); } [Fact(DisplayName = "Properly maps Pk when is not auto incrementing")] public void MapingNotAutoIncPk() { var db = new SqlCeDocumentStore<MonkeyDocument>(_connectionStringName); var pkMap = db.TableMapping.PrimaryKeyMapping; Assert.Single(pkMap); Assert.Equal("Name", pkMap[0].PropertyName); Assert.Equal("Name", pkMap[0].ColumnName); Assert.Equal(typeof(string), pkMap[0].DataType); Assert.False(pkMap[0].IsAutoIncementing); } } } ```
1bdb8380-a850-4f2e-9ac8-1b256831158f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Bloom.Publish; using BloomTemp; using Chorus.VcsDrivers.Mercurial; using LibChorus.TestUtilities; using NUnit.Framework; using Palaso.IO; using Palaso.Progress.LogBox; namespace BloomTests { [TestFixture] public class SendReceiveTests { [Test] public void CreateOrLocate_FolderHasAccentedLetter_FindsIt() { using (var setup = new RepositorySetup("Abé Books")) { Assert.NotNull(HgRepository.CreateOrLocate(setup.Repository.PathToRepo, new ConsoleProgress())); } } [Test] public void CreateOrLocate_FolderHasAccentedLetter2_FindsIt() { using (var testRoot = new TemporaryFolder("bloom sr test")) { string path = Path.Combine(testRoot.FolderPath, "Abé Books"); Directory.CreateDirectory(path); Assert.NotNull(HgRepository.CreateOrLocate(path, new ConsoleProgress())); Assert.NotNull(HgRepository.CreateOrLocate(path, new ConsoleProgress())); } } } } ``` Disable 2 s/r tests that demonstrate known chorus problems
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Bloom.Publish; using BloomTemp; using Chorus.VcsDrivers.Mercurial; using LibChorus.TestUtilities; using NUnit.Framework; using Palaso.IO; using Palaso.Progress.LogBox; namespace BloomTests { [TestFixture] public class SendReceiveTests { [Test, Ignore("not yet")] public void CreateOrLocate_FolderHasAccentedLetter_FindsIt() { using (var setup = new RepositorySetup("Abé Books")) { Assert.NotNull(HgRepository.CreateOrLocate(setup.Repository.PathToRepo, new ConsoleProgress())); } } [Test, Ignore("not yet")] public void CreateOrLocate_FolderHasAccentedLetter2_FindsIt() { using (var testRoot = new TemporaryFolder("bloom sr test")) { string path = Path.Combine(testRoot.FolderPath, "Abé Books"); Directory.CreateDirectory(path); Assert.NotNull(HgRepository.CreateOrLocate(path, new ConsoleProgress())); Assert.NotNull(HgRepository.CreateOrLocate(path, new ConsoleProgress())); } } } } ```
bdf28392-c5d2-4e46-b771-fab7f5fc2019
{ "language": "C#" }
```c# using System; using System.Windows.Forms; namespace BZ2TerrainEditor { /// <summary> /// Main class. /// </summary> public static class Program { private static int editorInstances; /// <summary> /// Gets or sets the number of editor instances. /// The application will exit when the number of instaces equals 0. /// </summary> public static int EditorInstances { get { return editorInstances; } set { editorInstances = value; if (editorInstances == 0) { Application.Exit(); } } } /// <summary> /// Entry point. /// </summary> [STAThread] public static void Main() { Application.EnableVisualStyles(); Editor editor = new Editor(); editor.Show(); Application.Run(); } } } ``` Add command line parsing (for "Open With...")
```c# using System; using System.Windows.Forms; namespace BZ2TerrainEditor { /// <summary> /// Main class. /// </summary> public static class Program { private static int editorInstances; /// <summary> /// Gets or sets the number of editor instances. /// The application will exit when the number of instaces equals 0. /// </summary> public static int EditorInstances { get { return editorInstances; } set { editorInstances = value; if (editorInstances == 0) { Application.Exit(); } } } /// <summary> /// Entry point. /// </summary> [STAThread] public static void Main(string[] args) { Application.EnableVisualStyles(); Editor editor; if (args.Length > 0) editor = new Editor(args[0]); else editor = new Editor(); editor.Show(); Application.Run(); } } } ```
5b350de2-d8ac-4336-abc3-c94645b01837
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class ResetBallUI : NetworkBehaviour { private void OnGUI() { GUILayout.BeginArea(new Rect(Screen.width - 150, 10, 140, 40)); if (GUILayout.Button("Reset Ball Position")) { CmdResetBallPosition(); } GUILayout.EndArea(); } [Command] private void CmdResetBallPosition() { var ball = GameObject.FindGameObjectWithTag("Ball"); if(ball != null) { ball.GetComponent<Ball>().ResetPosition(); } } } ``` Fix reset ball ui for local and multiplayer
```c# using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.Networking.NetworkSystem; public class ResetBallUI : NetworkBehaviour { // Message handle for the client id message private short RESPAWN_MESSAGE = 1003; void OnServerStart() { NetworkServer.RegisterHandler(RESPAWN_MESSAGE, OnResetBallPosition); } private void OnGUI() { GUILayout.BeginArea(new Rect(Screen.width - 150, 10, 140, 40)); if (GUILayout.Button("Reset Ball Position")) { ResetBallPosition(); } GUILayout.EndArea(); } [Server] private void OnResetBallPosition(NetworkMessage netMsg) { ResetBallPosition(); } private void ResetBallPosition() { if (NetworkServer.connections.Count > 0 || !NetworkManager.singleton.isNetworkActive) { // If local or the server reset the ball position var ball = GameObject.FindGameObjectWithTag("Ball"); if(ball != null) { ball.GetComponent<Ball>().ResetPosition(); } } else { // Send an empty message of type respawn message NetworkManager.singleton.client.connection.Send(RESPAWN_MESSAGE, new EmptyMessage()); } } } ```
d32bf0dd-b82b-49c1-9ee5-f01a5b36d3ac
{ "language": "C#" }
```c# using System; using System.Timers; using Shell.Execute; namespace PiDashcam { public class StillCam { Timer timer; int imgcounter; public StillCam() { timer = new Timer(10000); timer.Elapsed += Timer_Elapsed; timer.Start(); imgcounter = 1; } public void Stop() { timer.Stop(); } void Timer_Elapsed(object sender, ElapsedEventArgs e) { ProgramLauncher.Execute("raspistill", String.Format("-o {0}.jpg",imgcounter++)); } } } ``` Change still image capture parameters.
```c# using System; using System.Timers; using Shell.Execute; namespace PiDashcam { public class StillCam { Timer timer; int imgcounter; public StillCam() { timer = new Timer(6000); timer.Elapsed += Timer_Elapsed; timer.Start(); imgcounter = 1; } public void Stop() { timer.Stop(); } void Timer_Elapsed(object sender, ElapsedEventArgs e) { ProgramLauncher.Execute("raspistill", String.Format("-h 1920 -v 1080 -n -o {0}.jpg",imgcounter++)); } } } ```
ad0e264e-21c8-448a-9336-c5dee35cf795
{ "language": "C#" }
```c# using CertiPay.Common.Logging; using NUnit.Framework; using System; using System.Threading; namespace CertiPay.Common.Tests.Logging { public class MetricLoggingExtensionsTests { private static readonly ILog Log = LogManager.GetLogger<MetricLoggingExtensionsTests>(); [Test] public void Use_Log_Timer_No_Identifier() { using (Log.Timer("Use_Log_Timer")) { // Cool stuff happens here } } [Test] public void Use_Log_Timer_With_Debug() { using (Log.Timer("Use_Log_Timer_With_Debug", level: LogLevel.Debug)) { // Debug tracking happens here } } [Test] public void Takes_Longer_Than_Threshold() { using (Log.Timer("Takes_Longer_Than_Threshold", warnIfExceeds: TimeSpan.FromMilliseconds(100))) { Thread.Sleep(TimeSpan.FromMilliseconds(150)); } } [Test] public void Object_Context_Provided() { using (Log.Timer("Object_Context_Provided", new { id = 10, userId = 12 })) { // Cool stuff happens here } } } }``` Tweak tests to reflect new interface for log timing
```c# using CertiPay.Common.Logging; using NUnit.Framework; using System; using System.Threading; namespace CertiPay.Common.Tests.Logging { public class MetricLoggingExtensionsTests { private static readonly ILog Log = LogManager.GetLogger<MetricLoggingExtensionsTests>(); [Test] public void Use_Log_Timer_No_Identifier() { using (Log.Timer("Use_Log_Timer")) { // Cool stuff happens here } } [Test] public void Takes_Longer_Than_Threshold() { using (Log.Timer("Takes_Longer_Than_Threshold", warnIfExceeds: TimeSpan.FromMilliseconds(100))) { Thread.Sleep(TimeSpan.FromMilliseconds(150)); } } [Test] public void Object_Context_Provided() { using (Log.Timer("Object_Context_Provided {id} {userId}", new { id = 10, userId = 12 })) { // Cool stuff happens here } } } }```
6af431af-f24d-4138-bb24-efbf86618458
{ "language": "C#" }
```c# using UnityEngine; public class ReturnToHiveState : State { Arrive arrive; public ReturnToHiveState(GameObject gameObject) : base(gameObject) { this.gameObject = gameObject; } public override void Enter() { arrive = gameObject.GetComponent<Arrive>(); arrive.targetGameObject = gameObject.transform.parent.gameObject; } public override void Exit() { } public override void Update() { if (Vector3.Distance(gameObject.transform.position, gameObject.transform.parent.transform.position) < 1.0f) { gameObject.transform.parent.GetComponent<BeeSpawner>().pollenCount += gameObject.GetComponent<Bee>().collectedPollen; gameObject.GetComponent<Bee>().collectedPollen = 0.0f; gameObject.GetComponent<StateMachine>().SwitchState(new ExploreState(gameObject)); } } } ``` Set targetGameObject = null on ReturnToHive state exit as this target was overriding the target position when the boids switched back to exploring
```c# using UnityEngine; public class ReturnToHiveState : State { Arrive arrive; public ReturnToHiveState(GameObject gameObject) : base(gameObject) { this.gameObject = gameObject; } public override void Enter() { arrive = gameObject.GetComponent<Arrive>(); arrive.targetGameObject = gameObject.transform.parent.gameObject; } public override void Exit() { arrive.targetGameObject = null; } public override void Update() { if (Vector3.Distance(gameObject.transform.position, gameObject.transform.parent.transform.position) < 1.0f) { gameObject.transform.parent.GetComponent<BeeSpawner>().pollenCount += gameObject.GetComponent<Bee>().collectedPollen; gameObject.GetComponent<Bee>().collectedPollen = 0.0f; gameObject.GetComponent<StateMachine>().SwitchState(new ExploreState(gameObject)); } } } ```
c92d9699-84f0-427a-94b0-c1bb4dd7e88b
{ "language": "C#" }
```c# namespace Veil.Compiler { internal partial class VeilTemplateCompiler { private static void EmitWriteExpression<T>(VeilCompilerState<T> state, SyntaxTreeNode.WriteExpressionNode node) { state.Emitter.LoadWriterToStack(); state.PushExpressionScopeOnStack(node.Expression); state.Emitter.LoadExpressionFromCurrentModelOnStack(node.Expression); if (node.HtmlEncode && node.Expression.ResultType == typeof(string)) { var method = typeof(Helpers).GetMethod("HtmlEncode"); state.Emitter.Call(method); } else { state.Emitter.CallWriteFor(node.Expression.ResultType); } } } }``` Tidy up error handling in WriteExpression
```c# using System.Reflection; namespace Veil.Compiler { internal partial class VeilTemplateCompiler { private static MethodInfo htmlEncodeMethod = typeof(Helpers).GetMethod("HtmlEncode"); private static void EmitWriteExpression<T>(VeilCompilerState<T> state, SyntaxTreeNode.WriteExpressionNode node) { state.Emitter.LoadWriterToStack(); state.PushExpressionScopeOnStack(node.Expression); state.Emitter.LoadExpressionFromCurrentModelOnStack(node.Expression); if (node.HtmlEncode) { if (node.Expression.ResultType != typeof(string)) throw new VeilCompilerException("Tried to HtmlEncode an expression that does not evaluate to a string"); state.Emitter.Call(htmlEncodeMethod); } else { state.Emitter.CallWriteFor(node.Expression.ResultType); } } } }```
a1d97ec3-f335-4a16-845e-48976fbdc00e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Witness.Controllers { public class SandboxController : Controller { public ActionResult Index() { return View(); } } } ``` Add short term caching to sandbox html response to avoid repeated download by the browser.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Witness.Controllers { public class SandboxController : Controller { public ActionResult Index() { Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(1)); return View(); } } } ```
47c2243b-568d-4481-90ac-0599aa7e1af9
{ "language": "C#" }
```c# namespace Sep.Git.Tfs.Core.TfsInterop { public class WrapperFor<T> { private readonly T _wrapped; public WrapperFor(T wrapped) { _wrapped = wrapped; } public T Unwrap() { return _wrapped; } public static T Unwrap(object wrapper) { return ((WrapperFor<T>)wrapper).Unwrap(); } } } ``` Make the generic type self-documenting.
```c# namespace Sep.Git.Tfs.Core.TfsInterop { public class WrapperFor<TFS_TYPE> { private readonly TFS_TYPE _wrapped; public WrapperFor(TFS_TYPE wrapped) { _wrapped = wrapped; } public TFS_TYPE Unwrap() { return _wrapped; } public static TFS_TYPE Unwrap(object wrapper) { return ((WrapperFor<TFS_TYPE>)wrapper).Unwrap(); } } } ```
ca7d09a7-237a-4b52-a9cc-fdd6eb402f0c
{ "language": "C#" }
```c# // Copyright 2020 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using JetBrains.Annotations; using Nuke.Common.Execution; using Nuke.Common.Tools.DotNet; namespace Nuke.Common.CI { [PublicAPI] [AttributeUsage(AttributeTargets.Class)] public class ShutdownDotNetBuildServerOnFinish : Attribute, IOnBuildFinished { public void OnBuildFinished(NukeBuild build) { // Note https://github.com/dotnet/cli/issues/11424 DotNetTasks.DotNet("build-server shutdown"); } } } ``` Disable logging for shutdown of dotnet process by default
```c# // Copyright 2020 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using JetBrains.Annotations; using Nuke.Common.Execution; using Nuke.Common.Tools.DotNet; namespace Nuke.Common.CI { [PublicAPI] [AttributeUsage(AttributeTargets.Class)] public class ShutdownDotNetBuildServerOnFinish : Attribute, IOnBuildFinished { public bool EnableLogging { get; set; } public void OnBuildFinished(NukeBuild build) { // Note https://github.com/dotnet/cli/issues/11424 DotNetTasks.DotNet("build-server shutdown", logInvocation: EnableLogging, logOutput: EnableLogging); } } } ```
30a8e288-e2eb-454e-a150-56e7cc1e3f32
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.NHibernate 3.0.0")] ``` Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.NHibernate 3.0.0")] ```
b6cd03a6-b12f-431c-9367-cf314e2edbae
{ "language": "C#" }
```c# @model Dinamico.Models.ContentPage @{ Content.Define(re => { re.Title = "News page"; re.IconUrl = "{IconsUrl}/newspaper.png"; re.DefaultValue("Visible", false); re.RestrictParents("Container"); re.Sort(N2.Definitions.SortBy.PublishedDescending); }); } @Html.Partial("LayoutPartials/BlogContent") @using (Content.BeginScope(Content.Traverse.Parent())) { @Content.Render.Tokens("NewsFooter") } ``` Add tagging capability to Dinamico news page
```c# @model Dinamico.Models.ContentPage @{ Content.Define(re => { re.Title = "News page"; re.IconUrl = "{IconsUrl}/newspaper.png"; re.DefaultValue("Visible", false); re.RestrictParents("Container"); re.Sort(N2.Definitions.SortBy.PublishedDescending); re.Tags("Tags"); }); } @Html.Partial("LayoutPartials/BlogContent") @using (Content.BeginScope(Content.Traverse.Parent())) { @Content.Render.Tokens("NewsFooter") } ```
3c1cc699-84e9-4e2d-96d9-d780c7cd1be3
{ "language": "C#" }
```c# namespace WarehouseSystem.Web { using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using WarehouseSystem.Web.App_Start; public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DbConfig.Initialize(); AutoMapperConfig.Execute(); } } } ``` Set only Razor view Engine
```c# namespace WarehouseSystem.Web { using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using WarehouseSystem.Web.App_Start; public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DbConfig.Initialize(); AutoMapperConfig.Execute(); } } } ```
0f169de4-5fa9-418b-b622-6bc984f4476e
{ "language": "C#" }
```c# using System.Collections.Generic; using Newtonsoft.Json; using System; using Newtonsoft.Json.Converters; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public class DateMapping : MultiFieldMapping, IElasticType, IElasticCoreType { public DateMapping():base("date") { } /// <summary> /// The name of the field that will be stored in the index. Defaults to the property/field name. /// </summary> [JsonProperty("index_name")] public string IndexName { get; set; } [JsonProperty("store")] public bool? Store { get; set; } [JsonProperty("index"), JsonConverter(typeof(StringEnumConverter))] public NonStringIndexOption? Index { get; set; } [JsonProperty("format")] public string Format { get; set; } [JsonProperty("precision_step")] public int? PrecisionStep { get; set; } [JsonProperty("boost")] public double? Boost { get; set; } [JsonProperty("null_value")] public DateTime? NullValue { get; set; } [JsonProperty("ignore_malformed")] public bool? IgnoreMalformed { get; set; } [JsonProperty("doc_values")] public bool? DocValues { get; set; } [JsonProperty("numeric_resolution")] public NumericResolutionUnit NumericResolution { get; set; } } }``` Make numeric_resolution on date mapping nullable
```c# using System.Collections.Generic; using Newtonsoft.Json; using System; using Newtonsoft.Json.Converters; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public class DateMapping : MultiFieldMapping, IElasticType, IElasticCoreType { public DateMapping():base("date") { } /// <summary> /// The name of the field that will be stored in the index. Defaults to the property/field name. /// </summary> [JsonProperty("index_name")] public string IndexName { get; set; } [JsonProperty("store")] public bool? Store { get; set; } [JsonProperty("index"), JsonConverter(typeof(StringEnumConverter))] public NonStringIndexOption? Index { get; set; } [JsonProperty("format")] public string Format { get; set; } [JsonProperty("precision_step")] public int? PrecisionStep { get; set; } [JsonProperty("boost")] public double? Boost { get; set; } [JsonProperty("null_value")] public DateTime? NullValue { get; set; } [JsonProperty("ignore_malformed")] public bool? IgnoreMalformed { get; set; } [JsonProperty("doc_values")] public bool? DocValues { get; set; } [JsonProperty("numeric_resolution")] public NumericResolutionUnit? NumericResolution { get; set; } } }```
f76d8e53-56d0-4454-b5b9-8442002409e8
{ "language": "C#" }
```c# @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel <div class="das-panel das-panel--featured"> @if (Model.ReservedFundingToShow != null) { <h3 class="das-panel__heading">Apprenticeship funding secured</h3> <dl class="das-definition-list das-definition-list--with-separator"> <dt class="das-definition-list__title">Legal entity:</dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShowLegalEntityName</dd> <dt class="das-definition-list__title">Training course:</dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShow.CourseName</dd> <dt class="das-definition-list__title">Start and end date: </dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShow.StartDate.ToString("MMMM yyyy") to @Model.ReservedFundingToShow.EndDate.ToString("MMMM yyyy")</dd> </dl> } @if (Model.RecentlyAddedReservationId != null && Model.ReservedFundingToShow?.ReservationId != Model.RecentlyAddedReservationId) { <p>We're dealing with your request for funding, please check back later.</p> } <p><a href="@Url.ReservationsAction("reservations")" class="das-panel__link">Check and secure funding now</a> </p> </div>``` Remove nested div to fix style issue
```c# @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel @if (Model.ReservedFundingToShow != null) { <h3 class="das-panel__heading">Apprenticeship funding secured</h3> <dl class="das-definition-list das-definition-list--with-separator"> <dt class="das-definition-list__title">Legal entity:</dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShowLegalEntityName</dd> <dt class="das-definition-list__title">Training course:</dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShow.CourseName</dd> <dt class="das-definition-list__title">Start and end date: </dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShow.StartDate.ToString("MMMM yyyy") to @Model.ReservedFundingToShow.EndDate.ToString("MMMM yyyy")</dd> </dl> } @if (Model.RecentlyAddedReservationId != null && Model.ReservedFundingToShow?.ReservationId != Model.RecentlyAddedReservationId) { <p>We're dealing with your request for funding, please check back later.</p> } <p><a href="@Url.ReservationsAction("reservations")" class="das-panel__link">Check and secure funding now</a> </p>```
fddb014f-b504-4c9f-b65e-01009da45d8e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Microsoft.Azure.Mobile.Server; using DailySoccer.Shared.Models; namespace DailySoccerAppService.Controllers { public class MatchesController : ApiController { public ApiServices Services { get; set; } [HttpGet] public GetMatchesRespond GetMatches(GetMatchesRequest request) { var now = DateTime.Now; var matches = new List<MatchInformation> { new MatchInformation { Id = 1, BeginDate = now, LeagueName = "Premier League", TeamHome = new TeamInformation { Id = 1, Name = "FC Astana", CurrentScore = 1, CurrentPredictionPoints = 7, WinningPredictionPoints = 5 }, TeamAway = new TeamInformation { Id = 2, Name = "Atletico Madrid", CurrentScore = 0, CurrentPredictionPoints = 3, }, }, }; return new GetMatchesRespond { CurrentDate = now, AccountInfo = new AccountInformation { Points = 255, RemainingGuessAmount = 5, CurrentOrderedCoupon = 15 }, Matches = matches }; } } } ``` Add basic GET & POST methods into the MatchServices.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Microsoft.Azure.Mobile.Server; using DailySoccer.Shared.Models; namespace DailySoccerAppService.Controllers { public class MatchesController : ApiController { public ApiServices Services { get; set; } // GET: api/Matches [HttpGet] public string Get() { return "Respond by GET method"; } [HttpPost] public string Post(int id) { return "Respond by POST method, your ID: " + id; } [HttpPost] public GetMatchesRespond GetMatches(GetMatchesRequest request) { var now = DateTime.Now; var matches = new List<MatchInformation> { new MatchInformation { Id = 1, BeginDate = now, LeagueName = "Premier League", TeamHome = new TeamInformation { Id = 1, Name = "FC Astana", CurrentScore = 1, CurrentPredictionPoints = 7, WinningPredictionPoints = 5 }, TeamAway = new TeamInformation { Id = 2, Name = "Atletico Madrid", CurrentScore = 0, CurrentPredictionPoints = 3, }, }, }; return new GetMatchesRespond { CurrentDate = now, AccountInfo = new AccountInformation { Points = 255, RemainingGuessAmount = 5, CurrentOrderedCoupon = 15 }, Matches = matches }; } } } ```
0a1586dc-4b2b-4c76-bab0-0170fcd39af7
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Windows; using System.Windows.Documents; using System.Windows.Threading; namespace Smaller { public class RunJobController { private static readonly EventWaitHandle _showSignal = new EventWaitHandle(false, EventResetMode.AutoReset, "Smaller.ShowSignal"); public void TriggerRunJobs() { _showSignal.Set(); } private RunJobController() { StartListenForJobs(); } private static readonly RunJobController _instance = new RunJobController(); public static RunJobController Instance { get { return _instance; } } private void RunJobs() { Action x = () => { //if (Application.Current.MainWindow == null) //{ // Application.Current.MainWindow = new MainWindow(); // Application.Current.MainWindow.Show(); //} new JobRunner().Run(); }; Application.Current.Dispatcher.Invoke(x, DispatcherPriority.Send); } private void StartListenForJobs() { new Thread(() => { while (true) { _showSignal.WaitOne(); RunJobs(); } }).Start(); } } } ``` Fix bug where Smaller wouldn't exit properly
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Windows; using System.Windows.Documents; using System.Windows.Threading; namespace Smaller { public class RunJobController { private static readonly EventWaitHandle _showSignal = new EventWaitHandle(false, EventResetMode.AutoReset, "Smaller.ShowSignal"); public void TriggerRunJobs() { _showSignal.Set(); } private RunJobController() { StartListenForJobs(); } private static readonly RunJobController _instance = new RunJobController(); public static RunJobController Instance { get { return _instance; } } private void RunJobs() { Action x = () => { //if (Application.Current.MainWindow == null) //{ // Application.Current.MainWindow = new MainWindow(); // Application.Current.MainWindow.Show(); //} new JobRunner().Run(); }; Application.Current.Dispatcher.Invoke(x, DispatcherPriority.Send); } private void StartListenForJobs() { new Thread(() => { // only wait for signals while the app is running while (Application.Current != null) { if (_showSignal.WaitOne(500)) { RunJobs(); } } }).Start(); } } } ```
c837bef6-f8f0-42b8-b53c-ea7a5ad6163f
{ "language": "C#" }
```c# using System; namespace TAPCfg { public class EthernetFrame { private byte[] data; private byte[] src = new byte[6]; private byte[] dst = new byte[6]; private int etherType; public EthernetFrame(byte[] data) { this.data = data; Array.Copy(data, 0, dst, 0, 6); Array.Copy(data, 6, src, 0, 6); etherType = (data[12] << 8) | data[13]; } public byte[] Data { get { return data; } } public int Length { get { return data.Length; } } public byte[] SourceAddress { get { return src; } } public byte[] DestinationAddress { get { return dst; } } public int EtherType { get { return etherType; } } public byte[] Payload { get { byte[] ret = new byte[data.Length - 14]; Array.Copy(data, 14, ret, 0, ret.Length); return ret; } } } } ``` Add EtherType enumeration for some types (not all)
```c# using System; namespace TAPCfg { public enum EtherType : int { InterNetwork = 0x0800, ARP = 0x0806, RARP = 0x8035, AppleTalk = 0x809b, AARP = 0x80f3, InterNetworkV6 = 0x86dd, CobraNet = 0x8819, } public class EthernetFrame { private byte[] data; private byte[] src = new byte[6]; private byte[] dst = new byte[6]; private int etherType; public EthernetFrame(byte[] data) { this.data = data; Array.Copy(data, 0, dst, 0, 6); Array.Copy(data, 6, src, 0, 6); etherType = (data[12] << 8) | data[13]; } public byte[] Data { get { return data; } } public int Length { get { return data.Length; } } public byte[] SourceAddress { get { return src; } } public byte[] DestinationAddress { get { return dst; } } public int EtherType { get { return etherType; } } public byte[] Payload { get { byte[] ret = new byte[data.Length - 14]; Array.Copy(data, 14, ret, 0, ret.Length); return ret; } } } } ```
287fca0d-5718-46ab-addb-5a0f89ae48b0
{ "language": "C#" }
```c# using System; using System.IO; namespace Cake.AppVeyor.Tests { public static class Keys { const string YOUR_APPVEYOR_API_TOKEN = "{APPVEYOR_APITOKEN}"; static string appVeyorApiToken; public static string AppVeyorApiToken { get { if (appVeyorApiToken == null) { // Check for a local file with a token first var localFile = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", ".appveyorapitoken"); if (File.Exists(localFile)) appVeyorApiToken = File.ReadAllText(localFile); // Next check for an environment variable if (string.IsNullOrEmpty(appVeyorApiToken)) appVeyorApiToken = Environment.GetEnvironmentVariable("appveyor_api_token"); // Finally use the const value if (string.IsNullOrEmpty(appVeyorApiToken)) appVeyorApiToken = YOUR_APPVEYOR_API_TOKEN; } return appVeyorApiToken; } } } } ``` Fix path to local key file
```c# using System; using System.IO; namespace Cake.AppVeyor.Tests { public static class Keys { const string YOUR_APPVEYOR_API_TOKEN = "{APPVEYOR_APITOKEN}"; static string appVeyorApiToken; public static string AppVeyorApiToken { get { if (appVeyorApiToken == null) { // Check for a local file with a token first var localFile = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", ".appveyorapitoken"); if (File.Exists(localFile)) appVeyorApiToken = File.ReadAllText(localFile); // Next check for an environment variable if (string.IsNullOrEmpty(appVeyorApiToken)) appVeyorApiToken = Environment.GetEnvironmentVariable("appveyor_api_token"); // Finally use the const value if (string.IsNullOrEmpty(appVeyorApiToken)) appVeyorApiToken = YOUR_APPVEYOR_API_TOKEN; } return appVeyorApiToken; } } } } ```
7a5e7794-8724-467c-918a-8b43ac7698b7
{ "language": "C#" }
```c# using System; using NUnit.Framework; using FbxSharp; namespace FbxSharpTests { [TestFixture] public class ObjectPrinterTest { [Test] public void QuoteQuotesAndEscapeStrings() { Assert.AreEqual("\"abcdefghijklmnopqrstuvwxyz\"", ObjectPrinter.quote("abcdefghijklmnopqrstuvwxyz")); Assert.AreEqual("\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", ObjectPrinter.quote("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assert.AreEqual("\"0123456789\"", ObjectPrinter.quote("0123456789")); Assert.AreEqual("\"`~!@#$%^&*()_+-=\"", ObjectPrinter.quote("`~!@#$%^&*()_+-=")); // Assert.AreEqual("\"\\\\\"", ObjectPrinter.quote("\\")); // Assert.AreEqual("\"\\\"\"", ObjectPrinter.quote("\"")); Assert.AreEqual("\"[]{}|;:',<.>/?\"", ObjectPrinter.quote("[]{}|;:',<.>/?")); Assert.AreEqual("\"\\r\"", ObjectPrinter.quote("\r")); Assert.AreEqual("\"\\n\"", ObjectPrinter.quote("\n")); Assert.AreEqual("\"\\t\"", ObjectPrinter.quote("\t")); } } } ``` Add a test with a specific writer.
```c# using System; using NUnit.Framework; using FbxSharp; using System.IO; namespace FbxSharpTests { [TestFixture] public class ObjectPrinterTest { [Test] public void QuoteQuotesAndEscapeStrings() { Assert.AreEqual("\"abcdefghijklmnopqrstuvwxyz\"", ObjectPrinter.quote("abcdefghijklmnopqrstuvwxyz")); Assert.AreEqual("\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", ObjectPrinter.quote("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assert.AreEqual("\"0123456789\"", ObjectPrinter.quote("0123456789")); Assert.AreEqual("\"`~!@#$%^&*()_+-=\"", ObjectPrinter.quote("`~!@#$%^&*()_+-=")); // Assert.AreEqual("\"\\\\\"", ObjectPrinter.quote("\\")); // Assert.AreEqual("\"\\\"\"", ObjectPrinter.quote("\"")); Assert.AreEqual("\"[]{}|;:',<.>/?\"", ObjectPrinter.quote("[]{}|;:',<.>/?")); Assert.AreEqual("\"\\r\"", ObjectPrinter.quote("\r")); Assert.AreEqual("\"\\n\"", ObjectPrinter.quote("\n")); Assert.AreEqual("\"\\t\"", ObjectPrinter.quote("\t")); } [Test] public void PrintPropertyPrintsTheProperty() { // given var prop = new PropertyT<double>("something"); var printer = new ObjectPrinter(); var writer = new StringWriter(); var expected = @" Name = something Type = Double (MonoType) Value = 0 SrcObjectCount = 0 DstObjectCount = 0 "; // when printer.PrintProperty(prop, writer); // then Assert.AreEqual(expected, writer.ToString()); } } } ```
7ea4aaec-43de-4ae0-b665-0e40aea3cce1
{ "language": "C#" }
```c# using System.Reflection; // 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("5.10.2.0")] [assembly: AssemblyFileVersion("5.10.2.0")] ``` Revert "Bump WebApi version to 5.10.3"
```c# using System.Reflection; // 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("5.10.1.0")] [assembly: AssemblyFileVersion("5.10.1.0")] ```
e6323a69-da9a-43f1-99f4-c01be1a5d9d4
{ "language": "C#" }
```c# using System; using Roton.Emulation.Core; using Roton.Emulation.Data; using Roton.Emulation.Data.Impl; using Roton.Infrastructure.Impl; namespace Roton.Emulation.Interactions.Impl { [Context(Context.Original, 0x14)] [Context(Context.Super, 0x14)] public sealed class ForestInteraction : IInteraction { private readonly Lazy<IEngine> _engine; private IEngine Engine => _engine.Value; public ForestInteraction(Lazy<IEngine> engine) { _engine = engine; } public void Interact(IXyPair location, int index, IXyPair vector) { Engine.ClearForest(location); Engine.UpdateBoard(location); var forestIndex = Engine.State.ForestIndex; var forestSongLength = Engine.Sounds.Forest.Length; Engine.State.ForestIndex = (forestIndex + 2) % forestSongLength; Engine.PlaySound(3, Engine.Sounds.Forest, forestIndex, 2); if (!Engine.Alerts.Forest) return; Engine.SetMessage(0xC8, Engine.Alerts.ForestMessage); Engine.Alerts.Forest = false; } } }``` Fix a forest crash in ZZT.
```c# using System; using Roton.Emulation.Core; using Roton.Emulation.Data; using Roton.Emulation.Data.Impl; using Roton.Infrastructure.Impl; namespace Roton.Emulation.Interactions.Impl { [Context(Context.Original, 0x14)] [Context(Context.Super, 0x14)] public sealed class ForestInteraction : IInteraction { private readonly Lazy<IEngine> _engine; private IEngine Engine => _engine.Value; public ForestInteraction(Lazy<IEngine> engine) { _engine = engine; } public void Interact(IXyPair location, int index, IXyPair vector) { Engine.ClearForest(location); Engine.UpdateBoard(location); var forestSongLength = Engine.Sounds.Forest.Length; var forestIndex = Engine.State.ForestIndex % forestSongLength; Engine.State.ForestIndex = (forestIndex + 2) % forestSongLength; Engine.PlaySound(3, Engine.Sounds.Forest, forestIndex, 2); if (!Engine.Alerts.Forest) return; Engine.SetMessage(0xC8, Engine.Alerts.ForestMessage); Engine.Alerts.Forest = false; } } }```
8bc0c9df-345f-4654-b090-a73b6ddd918f
{ "language": "C#" }
```c# //------------------------------------------------------------------------------- // <copyright file="NewtonsoftJsonMessageSerializer.cs" company="MMS AG"> // Copyright (c) MMS AG, 2008-2015 // </copyright> //------------------------------------------------------------------------------- namespace MMS.ServiceBus.Pipeline { using System; using System.IO; using Newtonsoft.Json; public class NewtonsoftJsonMessageSerializer : IMessageSerializer { public string ContentType { get { return "application/json"; } } public void Serialize(object message, Stream body) { var streamWriter = new StreamWriter(body); var writer = new JsonTextWriter(streamWriter); var serializer = new JsonSerializer(); serializer.Serialize(writer, message); streamWriter.Flush(); body.Flush(); body.Position = 0; } public object Deserialize(Stream body, Type messageType) { var streamReader = new StreamReader(body); var reader = new JsonTextReader(streamReader); var serializer = new JsonSerializer(); return serializer.Deserialize(reader, messageType); } } }``` Enable configuration of Json Serializer
```c# //------------------------------------------------------------------------------- // <copyright file="NewtonsoftJsonMessageSerializer.cs" company="MMS AG"> // Copyright (c) MMS AG, 2008-2015 // </copyright> //------------------------------------------------------------------------------- namespace MMS.ServiceBus.Pipeline { using System; using System.IO; using Newtonsoft.Json; public class NewtonsoftJsonMessageSerializer : IMessageSerializer { private readonly Func<JsonSerializerSettings> settings; public NewtonsoftJsonMessageSerializer() : this(() => null) { } public NewtonsoftJsonMessageSerializer(Func<JsonSerializerSettings> settings) { this.settings = settings; } public string ContentType { get { return "application/json"; } } public void Serialize(object message, Stream body) { var streamWriter = new StreamWriter(body); var writer = new JsonTextWriter(streamWriter); var serializer = JsonSerializer.Create(this.settings()); serializer.Serialize(writer, message); streamWriter.Flush(); body.Flush(); body.Position = 0; } public object Deserialize(Stream body, Type messageType) { var streamReader = new StreamReader(body); var reader = new JsonTextReader(streamReader); var serializer = JsonSerializer.Create(this.settings()); return serializer.Deserialize(reader, messageType); } } }```
da0c2518-10a6-46e1-8cd7-dd955c12e871
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContextExtensions.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the context extensions class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.InMemory { using System.Collections.Generic; using Kephas.Data.Capabilities; using Kephas.Diagnostics.Contracts; using Kephas.Services; /// <summary> /// Extension methods for <see cref="IContext"/>. /// </summary> public static class ContextExtensions { /// <summary> /// Gets the initial data. /// </summary> /// <param name="context">The context to act on.</param> /// <returns> /// An enumeration of entity information. /// </returns> public static IEnumerable<IEntityInfo> GetInitialData(this IContext context) { Requires.NotNull(context, nameof(context)); return context[nameof(InMemoryDataContextConfiguration.InitialData)] as IEnumerable<IEntityInfo>; } /// <summary> /// Sets the initial data. /// </summary> /// <param name="context">The context to act on.</param> /// <param name="initialData">The initial data.</param> public static void SetInitialData(this IContext context, IEnumerable<IEntityInfo> initialData) { Requires.NotNull(context, nameof(context)); context[nameof(InMemoryDataContextConfiguration.InitialData)] = initialData; } } }``` Allow context to be null when querying for initial data.
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContextExtensions.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the context extensions class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.InMemory { using System.Collections.Generic; using Kephas.Data.Capabilities; using Kephas.Diagnostics.Contracts; using Kephas.Services; /// <summary> /// Extension methods for <see cref="IContext"/>. /// </summary> public static class ContextExtensions { /// <summary> /// Gets the initial data. /// </summary> /// <param name="context">The context to act on.</param> /// <returns> /// An enumeration of entity information. /// </returns> public static IEnumerable<IEntityInfo> GetInitialData(this IContext context) { return context?[nameof(InMemoryDataContextConfiguration.InitialData)] as IEnumerable<IEntityInfo>; } /// <summary> /// Sets the initial data. /// </summary> /// <param name="context">The context to act on.</param> /// <param name="initialData">The initial data.</param> public static void SetInitialData(this IContext context, IEnumerable<IEntityInfo> initialData) { Requires.NotNull(context, nameof(context)); context[nameof(InMemoryDataContextConfiguration.InitialData)] = initialData; } } }```
55275727-6c40-470f-80f7-2d75bef05175
{ "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 System; using Microsoft.AspNet.Security.DataProtection.KeyManagement; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection.Fallback; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Security.DataProtection { public class DefaultDataProtectionProvider : IDataProtectionProvider { private readonly IDataProtectionProvider _innerProvider; public DefaultDataProtectionProvider() { // use DI defaults var collection = new ServiceCollection(); var defaultServices = DataProtectionServices.GetDefaultServices(); collection.Add(defaultServices); var serviceProvider = collection.BuildServiceProvider(); _innerProvider = (IDataProtectionProvider)serviceProvider.GetService(typeof(IDataProtectionProvider)); CryptoUtil.Assert(_innerProvider != null, "_innerProvider != null"); } public DefaultDataProtectionProvider( [NotNull] IOptions<DataProtectionOptions> optionsAccessor, [NotNull] IKeyManager keyManager) { KeyRingBasedDataProtectionProvider rootProvider = new KeyRingBasedDataProtectionProvider(new KeyRingProvider(keyManager)); var options = optionsAccessor.Options; _innerProvider = (!String.IsNullOrEmpty(options.ApplicationDiscriminator)) ? (IDataProtectionProvider)rootProvider.CreateProtector(options.ApplicationDiscriminator) : rootProvider; } public IDataProtector CreateProtector([NotNull] string purpose) { return _innerProvider.CreateProtector(purpose); } } } ``` Change GetService call to GetRequiredService
```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 System; using Microsoft.AspNet.Security.DataProtection.KeyManagement; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection.Fallback; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Security.DataProtection { public class DefaultDataProtectionProvider : IDataProtectionProvider { private readonly IDataProtectionProvider _innerProvider; public DefaultDataProtectionProvider() { // use DI defaults var collection = new ServiceCollection(); var defaultServices = DataProtectionServices.GetDefaultServices(); collection.Add(defaultServices); var serviceProvider = collection.BuildServiceProvider(); _innerProvider = serviceProvider.GetRequiredService<IDataProtectionProvider>(); } public DefaultDataProtectionProvider( [NotNull] IOptions<DataProtectionOptions> optionsAccessor, [NotNull] IKeyManager keyManager) { KeyRingBasedDataProtectionProvider rootProvider = new KeyRingBasedDataProtectionProvider(new KeyRingProvider(keyManager)); var options = optionsAccessor.Options; _innerProvider = (!String.IsNullOrEmpty(options.ApplicationDiscriminator)) ? (IDataProtectionProvider)rootProvider.CreateProtector(options.ApplicationDiscriminator) : rootProvider; } public IDataProtector CreateProtector([NotNull] string purpose) { return _innerProvider.CreateProtector(purpose); } } } ```
b07f689a-f770-485a-8aab-5e5d4ac9dcab
{ "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.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmap; private string lookupString => beatmap.OnlineBeatmapID > 0 ? beatmap.OnlineBeatmapID.ToString() : $@"lookup?checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}"; public GetBeatmapRequest(BeatmapInfo beatmap) { this.beatmap = beatmap; } protected override string Target => $@"beatmaps/{lookupString}"; } } ``` Simplify beatmap lookup to use a single endpoint
```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.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmap; public GetBeatmapRequest(BeatmapInfo beatmap) { this.beatmap = beatmap; } protected override string Target => $@"beatmaps/lookup?id={beatmap.OnlineBeatmapID}&checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}"; } } ```
f311d773-7602-4811-bb60-f05729d0a233
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("DanTup's DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")] [assembly: AssemblyProduct("DanTup's DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")] [assembly: AssemblyCompany("Danny Tuppeny")] [assembly: AssemblyCopyright("Copyright Danny Tuppeny © 2014")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.1.*")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: InternalsVisibleTo("DanTup.DartAnalysis.Tests")] ``` Remove name from assembly info; this looks silly on NuGet.
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")] [assembly: AssemblyProduct("DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")] [assembly: AssemblyCompany("Danny Tuppeny")] [assembly: AssemblyCopyright("Copyright Danny Tuppeny © 2014")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.1.*")] [assembly: InternalsVisibleTo("DanTup.DartAnalysis.Tests")] ```
f2f9a00e-3090-4e62-8f7c-e4f1a329b33b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; namespace Mvc52Application.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { string foo = ConfigurationManager.AppSettings["foo"]; ViewBag.Message = String.Format("The value of setting foo is: '{0}'", foo); return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }``` Add some test tracing to Index action
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Web; using System.Web.Mvc; namespace Mvc52Application.Controllers { public class HomeController : Controller { public ActionResult Index() { Trace.TraceInformation("{0}: This is an informational trace message", DateTime.Now); Trace.TraceWarning("{0}: Here is trace warning", DateTime.Now); Trace.TraceError("{0}: Something is broken; tracing an error!", DateTime.Now); return View(); } public ActionResult About() { string foo = ConfigurationManager.AppSettings["foo"]; ViewBag.Message = String.Format("The value of setting foo is: '{0}'", foo); return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }```
c4da98b5-56ea-4f3c-ba57-edd8f1ea4e41
{ "language": "C#" }
```c# using ErgastApi.Client.Attributes; using ErgastApi.Responses; namespace ErgastApi.Requests { public class SeasonListRequest : StandardRequest<SeasonResponse> { // Value not used // ReSharper disable once UnassignedGetOnlyAutoProperty [UrlTerminator, UrlSegment("seasons")] protected object Seasons { get; } } }``` Support driver constructor standing parameter for season list request
```c# using ErgastApi.Client.Attributes; using ErgastApi.Responses; namespace ErgastApi.Requests { public class SeasonListRequest : StandardRequest<SeasonResponse> { [UrlSegment("constructorStandings")] public int? ConstructorStanding { get; set; } [UrlSegment("driverStandings")] public int? DriverStanding { get; set; } // Value not used // ReSharper disable once UnassignedGetOnlyAutoProperty [UrlTerminator, UrlSegment("seasons")] protected object Seasons { get; } } }```
a4b4a029-a08c-4e98-9496-c93c9c96c187
{ "language": "C#" }
```c# using System.Threading.Tasks; using Sinch.ServerSdk.Callouts; using Sinch.WebApiClient; public interface ICalloutApiEndpoints { [HttpPost("calling/v1/callouts/")] Task<CalloutResponse> Callout([ToBody] CalloutRequest request); }``` Remove API route trailing slash to avoid AWS API Gateway modification
```c# using System.Threading.Tasks; using Sinch.ServerSdk.Callouts; using Sinch.WebApiClient; public interface ICalloutApiEndpoints { [HttpPost("calling/v1/callouts")] Task<CalloutResponse> Callout([ToBody] CalloutRequest request); }```
3850a251-d6bc-4f28-a899-0d3dfa35d42e
{ "language": "C#" }
```c# namespace ImGui.Development { public class GUIDebug { public static void SetWindowPosition(string windowName, Point position) { var possibleWindow = Application.ImGuiContext.WindowManager.Windows.Find(window => window.Name == windowName); if (possibleWindow != null) { possibleWindow.Position = position; } } } }``` Add DebugBox for debugging issues in popup windows
```c# using ImGui.Rendering; namespace ImGui.Development { public class GUIDebug { public static void SetWindowPosition(string windowName, Point position) { var possibleWindow = Application.ImGuiContext.WindowManager.Windows.Find(window => window.Name == windowName); if (possibleWindow != null) { possibleWindow.Position = position; } } } } namespace ImGui { public partial class GUI { public static void DebugBox(int id, Rect rect, Color color) { var window = GetCurrentWindow(); if (window.SkipItems) return; //get or create the root node var container = window.AbsoluteVisualList; var node = (Node)container.Find(visual => visual.Id == id); if (node == null) { //create node node = new Node(id, $"DebugBox<{id}>"); node.UseBoxModel = true; node.RuleSet.Replace(GUISkin.Current[GUIControlName.Box]); node.RuleSet.BackgroundColor = color; container.Add(node); } node.ActiveSelf = true; // last item state window.TempData.LastItemState = node.State; // rect node.Rect = window.GetRect(rect); using (var dc = node.RenderOpen()) { dc.DrawBoxModel(node.RuleSet, node.Rect); } } } }```
38584d85-af06-4063-a444-37a10b7a2a84
{ "language": "C#" }
```c# namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account { public class LegalEntity { public long Id { get; set; } public string Name { get; set; } } }``` Change legal entity to include the CompanyNumber, RegisteredAddress and DateOfIncorporation
```c# using System; namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account { public class LegalEntity { public long Id { get; set; } public string CompanyNumber { get; set; } public string Name { get; set; } public string RegisteredAddress { get; set; } public DateTime DateOfIncorporation { get; set; } } }```
93a69638-5e3b-41f6-86df-2c646f4910a5
{ "language": "C#" }
```c# namespace Akiba.Core { using System.IO; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; internal class Configuration { public const string ConfigurationName = "configuration.yaml"; public enum ScreenModes : ushort { Windowed, Fullscreen, Borderless, }; public ushort FramesPerSecond { get; private set; } = 60; public ushort RenderingResolutionWidth { get; private set; } = 1920; public ushort RenderingResolutionHeight { get; private set; } = 1080; public ScreenModes ScreenMode { get; private set; } = ScreenModes.Fullscreen; public bool VerticalSynchronization { get; private set; } = false; public bool AntiAliasing { get; private set; } = false; public bool HideCursor { get; private set; } = false; public bool PreventSystemSleep { get; private set; } = true; public bool DisableMovies { get; private set; } = false; public Configuration Save() { var serializer = new SerializerBuilder().EmitDefaults().WithNamingConvention(new CamelCaseNamingConvention()).Build(); using (var streamWriter = new StreamWriter(ConfigurationName)) { serializer.Serialize(streamWriter, this); } return this; } public static Configuration LoadFromFile() { var deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(new CamelCaseNamingConvention()).Build(); using (var streamReader = new StreamReader(ConfigurationName)) { return deserializer.Deserialize<Configuration>(streamReader); } } } } ``` Set a more sensible default for the screen mode.
```c# namespace Akiba.Core { using System.IO; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; internal class Configuration { public const string ConfigurationName = "configuration.yaml"; public enum ScreenModes : ushort { Windowed, Fullscreen, Borderless, }; public ushort FramesPerSecond { get; private set; } = 60; public ushort RenderingResolutionWidth { get; private set; } = 1920; public ushort RenderingResolutionHeight { get; private set; } = 1080; public ScreenModes ScreenMode { get; private set; } = ScreenModes.Borderless; public bool VerticalSynchronization { get; private set; } = false; public bool AntiAliasing { get; private set; } = false; public bool HideCursor { get; private set; } = false; public bool PreventSystemSleep { get; private set; } = true; public bool DisableMovies { get; private set; } = false; public Configuration Save() { var serializer = new SerializerBuilder().EmitDefaults().WithNamingConvention(new CamelCaseNamingConvention()).Build(); using (var streamWriter = new StreamWriter(ConfigurationName)) { serializer.Serialize(streamWriter, this); } return this; } public static Configuration LoadFromFile() { var deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(new CamelCaseNamingConvention()).Build(); using (var streamReader = new StreamReader(ConfigurationName)) { return deserializer.Deserialize<Configuration>(streamReader); } } } } ```
6f97d628-6105-4d25-b901-9448979968f7
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { // Custom attribute to indicating a TypeDef is a discardable attribute. public class DiscardableAttribute : Attribute { public DiscardableAttribute() { } } } ``` Fix FxCop warning CA1018 (attributes should have AttributeUsage)
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { // Custom attribute to indicating a TypeDef is a discardable attribute. [AttributeUsage(AttributeTargets.All)] public class DiscardableAttribute : Attribute { public DiscardableAttribute() { } } } ```
d0c63d3a-a162-4139-8d27-91648146d613
{ "language": "C#" }
```c# using Gtk; using NLog; using SlimeSimulation.Controller.WindowController.Templates; namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent { class AdaptionPhaseControlBox : AbstractSimulationControlBox { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public AdaptionPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { AddControls(simulationStepAbstractWindowController, parentWindow); } private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { var controlInterfaceStartingValues = simulationStepAbstractWindowController.SimulationControlInterfaceValues; Add(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow)); Add(new SimulationStepNumberOfTimesComponent(simulationStepAbstractWindowController, parentWindow, controlInterfaceStartingValues)); Add(new ShouldFlowResultsBeDisplayedControlComponent(controlInterfaceStartingValues)); Add(new ShouldStepFromAllSourcesAtOnceControlComponent(controlInterfaceStartingValues)); Add(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow)); } } } ``` Add some changes to UI to make spacing equal for components
```c# using Gtk; using NLog; using SlimeSimulation.Controller.WindowController.Templates; namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent { class AdaptionPhaseControlBox : AbstractSimulationControlBox { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public AdaptionPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { AddControls(simulationStepAbstractWindowController, parentWindow); } private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { var controlInterfaceStartingValues = simulationStepAbstractWindowController.SimulationControlInterfaceValues; var container = new Table(6, 1, true); container.Attach(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow), 0, 1, 0, 1); container.Attach(new SimulationStepNumberOfTimesComponent(simulationStepAbstractWindowController, parentWindow, controlInterfaceStartingValues), 0, 1, 1, 3); container.Attach(new ShouldFlowResultsBeDisplayedControlComponent(controlInterfaceStartingValues), 0, 1, 3, 4); container.Attach(new ShouldStepFromAllSourcesAtOnceControlComponent(controlInterfaceStartingValues), 0, 1, 4, 5); container.Attach(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow), 0, 1, 5, 6); Add(container); } } } ```
8dce7311-44c3-4866-be07-774f6cfa5bd1
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new AudioCollectionManager<AdjustableAudioComponent>(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a seperate thread start processing the queue new Thread(() => manager.Update()).Start(); // wait a little for beginning of the update to start Thread.Sleep(4); Assert.DoesNotThrow(() => manager.Dispose()); } } } ``` Move test component to bottom of class
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new AudioCollectionManager<AdjustableAudioComponent>(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a seperate thread start processing the queue new Thread(() => manager.Update()).Start(); // wait a little for beginning of the update to start Thread.Sleep(4); Assert.DoesNotThrow(() => manager.Dispose()); } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } } ```
64fb2e62-b4c1-4a03-b0a2-26bce18175d2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ERMine.Core.Modeling { public class Attribute : IEntityRelationship { public string Label { get; set; } public string DataType { get; set; } public Domain Domain { get; set; } public bool IsNullable { get; set; } public bool IsSparse { get; set; } public bool IsImmutable { get; set; } public KeyType Key { get; set; } public bool IsPartOfPrimaryKey { get { return Key == KeyType.Primary; } set { Key = value ? KeyType.Primary : KeyType.None; } } public bool IsPartOfPartialKey { get { return Key == KeyType.Partial; } set { Key = value ? KeyType.Partial : KeyType.None; } } public bool IsMultiValued { get; set; } public bool IsDerived { get; set; } public string DerivedFormula { get; set; } public bool IsDefault { get; set; } public string DefaultFormula { get; set; } } } ``` Add quick check for attached domain
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ERMine.Core.Modeling { public class Attribute : IEntityRelationship { public string Label { get; set; } public string DataType { get; set; } public Domain Domain { get; set; } public bool IsConstrainedDomain { get { return Domain != null; } } public bool IsNullable { get; set; } public bool IsSparse { get; set; } public bool IsImmutable { get; set; } public KeyType Key { get; set; } public bool IsPartOfPrimaryKey { get { return Key == KeyType.Primary; } set { Key = value ? KeyType.Primary : KeyType.None; } } public bool IsPartOfPartialKey { get { return Key == KeyType.Partial; } set { Key = value ? KeyType.Partial : KeyType.None; } } public bool IsMultiValued { get; set; } public bool IsDerived { get; set; } public string DerivedFormula { get; set; } public bool IsDefault { get; set; } public string DefaultFormula { get; set; } } } ```
b41fcfab-1eac-45ff-9d04-5c98f6e93b03
{ "language": "C#" }
```c# using PS.Mothership.Core.Common.Template.Gen; using PS.Mothership.Core.Common.Template.Opp; using System; using System.Runtime.Serialization; namespace PS.Mothership.Core.Common.Dto.Application { [DataContract] public class OpportunitySummaryDto { [DataMember] public Guid OpportunityGuid { get; set; } [DataMember] public double Credit { get; set; } [DataMember] public double Debit { get; set; } [DataMember] public OppTypeOfTransactionEnum TypeOfTransactionKey { get; set; } [DataMember] public string Vendor { get; set; } [DataMember] public string Model { get; set; } [DataMember] public GenOpportunityStatusEnum OpportunityStatusKey { get; set; } [DataMember] public string ContractLengthDescription { get; set; } } } ``` Revert to use ProductType since this is all that is needed in the summary, as it is the only thing shown in the opportunity summary, in the offer page
```c# using PS.Mothership.Core.Common.Template.Gen; using PS.Mothership.Core.Common.Template.Opp; using System; using System.Runtime.Serialization; namespace PS.Mothership.Core.Common.Dto.Application { [DataContract] public class OpportunitySummaryDto { [DataMember] public Guid OpportunityGuid { get; set; } [DataMember] public double Credit { get; set; } [DataMember] public double Debit { get; set; } [DataMember] public OppTypeOfTransactionEnum TypeOfTransactionKey { get; set; } [DataMember] public string ProductType { get; set; } [DataMember] public GenOpportunityStatusEnum OpportunityStatusKey { get; set; } [DataMember] public string ContractLengthDescription { get; set; } } } ```
2324d4ad-01ca-4070-a37f-ad0f885eeb9c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Bex.Extensions { internal static class UriExtensions { internal static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri) { var uriString = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString; var queryIndex = uriString.IndexOf("?", StringComparison.OrdinalIgnoreCase); if (queryIndex == -1) { return Enumerable.Empty<KeyValuePair<string, string>>(); } var query = uriString.Substring(queryIndex + 1); return query.Split('&') .Where(x => !string.IsNullOrEmpty(x)) .Select(x => x.Split('=')) .Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null)); } } } ``` Use the Query property of the Uri
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Bex.Extensions { internal static class UriExtensions { internal static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri) { if (string.IsNullOrEmpty(uri.Query)) { return Enumerable.Empty<KeyValuePair<string, string>>(); } var query = uri.Query.TrimStart('?'); return query.Split('&') .Where(x => !string.IsNullOrEmpty(x)) .Select(x => x.Split('=')) .Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null)); } } } ```
068d1ec0-5230-43fc-b44d-9d76cbca6809
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ExCSS Parser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ExCSS CSS Parser")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("eb4daa16-725f-4c8f-9d74-b9b569d57f42")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.0.2")] [assembly: AssemblyFileVersion("2.0.2")] ``` Align assembly verions with package release 2.0.3
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ExCSS Parser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ExCSS CSS Parser")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("eb4daa16-725f-4c8f-9d74-b9b569d57f42")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.0.3")] [assembly: AssemblyFileVersion("2.0.3")] ```
288185e7-1643-4edb-8e66-3ba4a55bed24
{ "language": "C#" }
```c# namespace Octokit { public static class AcceptHeaders { public const string StableVersion = "application/vnd.github.v3"; public const string StableVersionHtml = "application/vnd.github.html"; public const string RedirectsPreviewThenStableVersionJson = "application/vnd.github.quicksilver-preview+json; charset=utf-8, application/vnd.github.v3+json; charset=utf-8"; public const string LicensesApiPreview = "application/vnd.github.drax-preview+json"; public const string ProtectedBranchesApiPreview = "application/vnd.github.loki-preview+json"; public const string StarCreationTimestamps = "application/vnd.github.v3.star+json"; public const string IssueLockingUnlockingApiPreview = "application/vnd.github.the-key-preview+json"; public const string CommitReferenceSha1Preview = "application/vnd.github.chitauri-preview+sha"; public const string SquashCommitPreview = "application/vnd.github.polaris-preview+json"; public const string MigrationsApiPreview = " application/vnd.github.wyandotte-preview+json"; public const string OrganizationPermissionsPreview = "application/vnd.github.ironman-preview+json"; } } ``` Add GPG Keys API preview header
```c# using System.Diagnostics.CodeAnalysis; namespace Octokit { public static class AcceptHeaders { public const string StableVersion = "application/vnd.github.v3"; public const string StableVersionHtml = "application/vnd.github.html"; public const string RedirectsPreviewThenStableVersionJson = "application/vnd.github.quicksilver-preview+json; charset=utf-8, application/vnd.github.v3+json; charset=utf-8"; public const string LicensesApiPreview = "application/vnd.github.drax-preview+json"; public const string ProtectedBranchesApiPreview = "application/vnd.github.loki-preview+json"; public const string StarCreationTimestamps = "application/vnd.github.v3.star+json"; public const string IssueLockingUnlockingApiPreview = "application/vnd.github.the-key-preview+json"; public const string CommitReferenceSha1Preview = "application/vnd.github.chitauri-preview+sha"; public const string SquashCommitPreview = "application/vnd.github.polaris-preview+json"; public const string MigrationsApiPreview = " application/vnd.github.wyandotte-preview+json"; public const string OrganizationPermissionsPreview = "application/vnd.github.ironman-preview+json"; [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpg")] public const string GpgKeysPreview = "application/vnd.github.cryptographer-preview+sha"; } } ```
0e6308fd-39b8-4a69-bce0-107e4302fe28
{ "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.Configuration; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Screens; using osu.Game.Localisation; using osu.Game.Screens; using osu.Game.Screens.Import; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class GeneralSettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.GeneralHeader; [BackgroundDependencyLoader(true)] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig, IPerformFromScreenRunner performer) { Children = new Drawable[] { new SettingsCheckbox { LabelText = DebugSettingsStrings.ShowLogOverlay, Current = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = DebugSettingsStrings.BypassFrontToBackPass, Current = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass) } }; Add(new SettingsButton { Text = DebugSettingsStrings.ImportFiles, Action = () => performer?.PerformFromScreen(menu => menu.Push(new FileImportScreen())) }); } } } ``` Add button to access latency comparer from game
```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.Configuration; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Screens; using osu.Game.Localisation; using osu.Game.Screens; using osu.Game.Screens.Import; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class GeneralSettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.GeneralHeader; [BackgroundDependencyLoader(true)] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig, IPerformFromScreenRunner performer) { Children = new Drawable[] { new SettingsCheckbox { LabelText = DebugSettingsStrings.ShowLogOverlay, Current = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = DebugSettingsStrings.BypassFrontToBackPass, Current = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass) }, new SettingsButton { Text = DebugSettingsStrings.ImportFiles, Action = () => performer?.PerformFromScreen(menu => menu.Push(new FileImportScreen())) }, new SettingsButton { Text = @"Run latency comparer", Action = () => performer?.PerformFromScreen(menu => menu.Push(new LatencyComparerScreen())) } }; } } } ```
482b2869-4971-4d49-b226-ce3819a54b5f
{ "language": "C#" }
```c# using System; using System.IO; using Ploeh.AutoFixture; namespace AppHarbor.Tests { public class TextWriterCustomization : ICustomization { public void Customize(IFixture fixture) { fixture.Customize<TextWriter>(x => x.FromFactory(() => { return Console.Out; })); } } } ``` Make sure to also customize Mock<TextWriter> and use same instance
```c# using System.IO; using Moq; using Ploeh.AutoFixture; namespace AppHarbor.Tests { public class TextWriterCustomization : ICustomization { public void Customize(IFixture fixture) { var textWriterMock = new Mock<TextWriter>(); fixture.Customize<TextWriter>(x => x.FromFactory(() => { return textWriterMock.Object; })); fixture.Customize<Mock<TextWriter>>(x => x.FromFactory(() => { return textWriterMock; })); } } } ```
adedfd04-8b40-494c-a6a4-f4e2c252730b
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; using System.Collections.Generic; namespace Stripe { public class StripeSubscriptionUpdateOptions : StripeSubscriptionCreateOptions { [JsonProperty("prorate")] public bool? Prorate { get; set; } } }``` Add "plan" to StripSubscriptionUpdateOptions so we can change plans.
```c# using System; using Newtonsoft.Json; using System.Collections.Generic; namespace Stripe { public class StripeSubscriptionUpdateOptions : StripeSubscriptionCreateOptions { [JsonProperty("prorate")] public bool? Prorate { get; set; } [JsonProperty("plan")] public string PlanId { get; set; } } }```
75b9c1d7-aebc-4b91-adb2-ec4c0af849c1
{ "language": "C#" }
```c# using System; using System.IO; namespace DarkMultiPlayerServer { public class LogExpire { private static string logDirectory { get { return Path.Combine(Server.universeDirectory, DarkLog.LogFolder); } } public static void ExpireLogs() { if (!Directory.Exists(logDirectory)) { //Screenshot directory is missing so there will be no screenshots to delete. return; } string[] logFiles = Directory.GetFiles(logDirectory); foreach (string logFile in logFiles) { Console.WriteLine("LogFile: " + logFile); //Check if the expireScreenshots setting is enabled if (Settings.settingsStore.expireLogs > 0) { //If the file is older than a day, delete it if (File.GetCreationTime(logFile).AddDays(Settings.settingsStore.expireLogs) < DateTime.Now) { DarkLog.Debug("Deleting saved log '" + logFile + "', reason: Expired!"); try { File.Delete(logFile); } catch (Exception e) { DarkLog.Error("Exception while trying to delete '" + logFile + "'!, Exception: " + e.Message); } } } } } } }``` Remove debugging line. Sorry RockyTV!
```c# using System; using System.IO; namespace DarkMultiPlayerServer { public class LogExpire { private static string logDirectory { get { return Path.Combine(Server.universeDirectory, DarkLog.LogFolder); } } public static void ExpireLogs() { if (!Directory.Exists(logDirectory)) { //Screenshot directory is missing so there will be no screenshots to delete. return; } string[] logFiles = Directory.GetFiles(logDirectory); foreach (string logFile in logFiles) { //Check if the expireScreenshots setting is enabled if (Settings.settingsStore.expireLogs > 0) { //If the file is older than a day, delete it if (File.GetCreationTime(logFile).AddDays(Settings.settingsStore.expireLogs) < DateTime.Now) { DarkLog.Debug("Deleting saved log '" + logFile + "', reason: Expired!"); try { File.Delete(logFile); } catch (Exception e) { DarkLog.Error("Exception while trying to delete '" + logFile + "'!, Exception: " + e.Message); } } } } } } }```
e23fbe20-5ec5-4023-a00d-3a1481779cbe
{ "language": "C#" }
```c# using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Vocal.Model; namespace Vocal.Core { public class JsonCommandLoader { const string DefaultConfigFile = "commandsTemplate.json"; const string WriteableConfigFile = "commands.json"; public static IEnumerable<IVoiceCommand> LoadCommandsFromConfiguration() { if(!File.Exists(WriteableConfigFile)) { CreateWriteableConfigFile(DefaultConfigFile, WriteableConfigFile); } if (!File.Exists(WriteableConfigFile)) throw new Exception($"There was an error creating the command configuration file {WriteableConfigFile}. You may need to create this file manually."); return JsonConvert.DeserializeObject<VoiceCommand[]>(File.ReadAllText(WriteableConfigFile)); } public static void CreateWriteableConfigFile(string source, string destination) { if (!File.Exists(source)) throw new Exception($"The source configuration file {source} does not exist. A writeable configuration cannot be created. See the documentation for more details."); File.Copy(source, destination); } } } ``` Move command file to appdata
```c# using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using Vocal.Model; namespace Vocal.Core { public class JsonCommandLoader { const string AppDataFolder = "VocalBuildEngine"; const string DefaultConfigFile = "commandsTemplate.json"; const string WriteableCommandFile = "commands.json"; public static IEnumerable<IVoiceCommand> LoadCommandsFromConfiguration() { var commandFile = GetDefaultPath(WriteableCommandFile); if (!File.Exists(commandFile)) { var file = new FileInfo(commandFile); if (!Directory.Exists(file.Directory.FullName)) Directory.CreateDirectory(file.Directory.FullName); CreateWriteableConfigFile(DefaultConfigFile, commandFile); } if (!File.Exists(commandFile)) throw new Exception($"There was an error creating the command configuration file {commandFile}. You may need to create this file manually."); return JsonConvert.DeserializeObject<VoiceCommand[]>(File.ReadAllText(commandFile)); } public static void CreateWriteableConfigFile(string source, string destination) { if (!File.Exists(source)) throw new Exception($"The source configuration file {source} does not exist. A writeable configuration cannot be created. See the documentation for more details."); File.Copy(source, destination); } public static string GetDefaultPath(string fileName) { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), AppDataFolder, fileName); } } } ```
5c11540a-1023-4e96-ae31-ee7fe032c823
{ "language": "C#" }
```c# @using FormFactory @model PropertyVm <input type="hidden" name="@Model.Name" id="MyFileSubmitPlaceHolder" />@*here to trick model binding into working :( *@ <input type="file" name="@Model.Name" @Model.Readonly() @Model.Disabled() />``` Hide file input if readonly
```c# @using FormFactory @model PropertyVm @if(!Model.Readonly) { <input type="hidden" name="@Model.Name" /> @*here to trick model binding into working :( *@ <input type="file" name="@Model.Name" @Model.Readonly() @Model.Disabled() /> }```
fe7de394-ae5e-4323-8633-377571e36fde
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Serialization; namespace Microsoft.CodeAnalysis.Host { interface IPersistentStorageLocationService : IWorkspaceService { string TryGetStorageLocation(Solution solution); } [ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared] internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService { [ImportingConstructor] public DefaultPersistentStorageLocationService() { } public string TryGetStorageLocation(Solution solution) { if (string.IsNullOrWhiteSpace(solution.FilePath)) return null; // Ensure that each unique workspace kind for any given solution has a unique // folder to store their data in. var checksums = new[] { Checksum.Create(solution.FilePath), Checksum.Create(solution.Workspace.Kind) }; var hashedName = Checksum.Create(WellKnownSynchronizationKind.Null, checksums).ToString(); var workingFolder = Path.Combine(Path.GetTempPath(), hashedName); return workingFolder; } } } ``` Switch to using LocalApplicationData folder
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Serialization; namespace Microsoft.CodeAnalysis.Host { interface IPersistentStorageLocationService : IWorkspaceService { string TryGetStorageLocation(Solution solution); } [ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared] internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService { [ImportingConstructor] public DefaultPersistentStorageLocationService() { } public string TryGetStorageLocation(Solution solution) { if (string.IsNullOrWhiteSpace(solution.FilePath)) return null; // Ensure that each unique workspace kind for any given solution has a unique // folder to store their data in. var checksums = new[] { Checksum.Create(solution.FilePath), Checksum.Create(solution.Workspace.Kind) }; var hashedName = Checksum.Create(WellKnownSynchronizationKind.Null, checksums).ToString(); var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create); var workingFolder = Path.Combine(appDataFolder, "Roslyn", hashedName); return workingFolder; } } } ```
de64459a-803a-4148-bec1-deeb917eb0fc
{ "language": "C#" }
```c# using System.Collections.Generic; using StockportContentApi.ContentfulModels; using StockportContentApi.Model; namespace StockportContentApi.ContentfulFactories { public class CommsContentfulFactory : IContentfulFactory<ContentfulCommsHomepage, CommsHomepage> { private readonly IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> _callToActionFactory; private readonly IContentfulFactory<ContentfulEvent, Event> _eventFactory; private readonly IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> _basicLinkFactory; public CommsContentfulFactory( IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> callToActionFactory, IContentfulFactory<ContentfulEvent, Event> eventFactory, IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> basicLinkFactory) { _callToActionFactory = callToActionFactory; _eventFactory = eventFactory; _basicLinkFactory = basicLinkFactory; } public CommsHomepage ToModel(ContentfulCommsHomepage model) { var callToActionBanner = _callToActionFactory.ToModel(model.CallToActionBanner); var displayEvent = _eventFactory.ToModel(model.WhatsOnInStockportEvent); var basicLinks = _basicLinkFactory.ToModel(model.UsefullLinks); return new CommsHomepage( model.Title, model.LatestNewsHeader, model.TwitterFeedHeader, model.InstagramFeedTitle, model.InstagramLink, model.FacebookFeedTitle, basicLinks, displayEvent, callToActionBanner ); } } } ``` Allow call to action banner to be optional
```c# using System.Collections.Generic; using StockportContentApi.ContentfulModels; using StockportContentApi.Model; namespace StockportContentApi.ContentfulFactories { public class CommsContentfulFactory : IContentfulFactory<ContentfulCommsHomepage, CommsHomepage> { private readonly IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> _callToActionFactory; private readonly IContentfulFactory<ContentfulEvent, Event> _eventFactory; private readonly IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> _basicLinkFactory; public CommsContentfulFactory( IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> callToActionFactory, IContentfulFactory<ContentfulEvent, Event> eventFactory, IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> basicLinkFactory) { _callToActionFactory = callToActionFactory; _eventFactory = eventFactory; _basicLinkFactory = basicLinkFactory; } public CommsHomepage ToModel(ContentfulCommsHomepage model) { var callToActionBanner = model.CallToActionBanner != null ? _callToActionFactory.ToModel(model.CallToActionBanner) : null; var displayEvent = _eventFactory.ToModel(model.WhatsOnInStockportEvent); var basicLinks = _basicLinkFactory.ToModel(model.UsefullLinks); return new CommsHomepage( model.Title, model.LatestNewsHeader, model.TwitterFeedHeader, model.InstagramFeedTitle, model.InstagramLink, model.FacebookFeedTitle, basicLinks, displayEvent, callToActionBanner ); } } } ```
b2275397-5d80-4c38-917f-776858f46f80
{ "language": "C#" }
```c# using System.Reflection; using System.Resources; 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("Treenumerable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jason Boyd")] [assembly: AssemblyProduct("Treenumerable")] [assembly: AssemblyCopyright("Copyright © Jason Boyd 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo("Treenumerable.Tests")] // 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.2.0")] [assembly: AssemblyFileVersion("1.2.0")] ``` Update assembly version to 2.0.0
```c# using System.Reflection; using System.Resources; 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("Treenumerable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jason Boyd")] [assembly: AssemblyProduct("Treenumerable")] [assembly: AssemblyCopyright("Copyright © Jason Boyd 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo("Treenumerable.Tests")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyFileVersion("2.0.0")] ```
5ba462df-55b3-4e19-843b-04d67b6b0c31
{ "language": "C#" }
```c# using System; using System.Collections.Immutable; using System.IO; using Microsoft.Extensions.Logging; using OmniSharp.Utilities; namespace OmniSharp.MSBuild.Discovery.Providers { internal class MonoInstanceProvider : MSBuildInstanceProvider { public MonoInstanceProvider(ILoggerFactory loggerFactory) : base(loggerFactory) { } public override ImmutableArray<MSBuildInstance> GetInstances() { if (!PlatformHelper.IsMono) { return ImmutableArray<MSBuildInstance>.Empty; } var path = PlatformHelper.GetMonoMSBuildDirPath(); if (path == null) { return ImmutableArray<MSBuildInstance>.Empty; } var toolsPath = Path.Combine(path, "15.0", "bin"); if (!Directory.Exists(toolsPath)) { return ImmutableArray<MSBuildInstance>.Empty; } var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase); var localMSBuildPath = FindLocalMSBuildDirectory(); if (localMSBuildPath != null) { var localRoslynPath = Path.Combine(localMSBuildPath, "Roslyn"); propertyOverrides.Add("CscToolPath", localRoslynPath); propertyOverrides.Add("CscToolExe", "csc.exe"); } return ImmutableArray.Create( new MSBuildInstance( "Mono", toolsPath, new Version(15, 0), DiscoveryType.Mono, propertyOverrides.ToImmutable())); } } } ``` Use correct path to MSBuild Roslyn folder on Mono
```c# using System; using System.Collections.Immutable; using System.IO; using Microsoft.Extensions.Logging; using OmniSharp.Utilities; namespace OmniSharp.MSBuild.Discovery.Providers { internal class MonoInstanceProvider : MSBuildInstanceProvider { public MonoInstanceProvider(ILoggerFactory loggerFactory) : base(loggerFactory) { } public override ImmutableArray<MSBuildInstance> GetInstances() { if (!PlatformHelper.IsMono) { return ImmutableArray<MSBuildInstance>.Empty; } var path = PlatformHelper.GetMonoMSBuildDirPath(); if (path == null) { return ImmutableArray<MSBuildInstance>.Empty; } var toolsPath = Path.Combine(path, "15.0", "bin"); if (!Directory.Exists(toolsPath)) { return ImmutableArray<MSBuildInstance>.Empty; } var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase); var localMSBuildPath = FindLocalMSBuildDirectory(); if (localMSBuildPath != null) { var localRoslynPath = Path.Combine(localMSBuildPath, "15.0", "Bin", "Roslyn"); propertyOverrides.Add("CscToolPath", localRoslynPath); propertyOverrides.Add("CscToolExe", "csc.exe"); } return ImmutableArray.Create( new MSBuildInstance( "Mono", toolsPath, new Version(15, 0), DiscoveryType.Mono, propertyOverrides.ToImmutable())); } } } ```
fb0dbf5c-a087-4996-8cf6-0520e71807a9
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Threading.Tasks; namespace NTwitch { public interface ITwitchClient { ConnectionState ConnectionState { get; } Task<IChannel> GetChannelAsync(ulong id); Task<IEnumerable<ITopGame>> GetTopGames(TwitchPageOptions options = null); Task<IEnumerable<IIngest>> GetIngestsAsync(); Task<IEnumerable<IChannel>> FindChannelsAsync(string query, TwitchPageOptions options = null); Task<IEnumerable<IGame>> FindGamesAsync(string query, bool islive = true); Task<IStream> GetStreamAsync(ulong id, StreamType type = StreamType.All); Task<IEnumerable<IStream>> FindStreamsAsync(string query, bool hls = true, TwitchPageOptions options = null); Task<IEnumerable<IStream>> GetStreamsAsync(string game = null, ulong[] channelids = null, string language = null, StreamType type = StreamType.All, TwitchPageOptions options = null); Task<IEnumerable<IFeaturedStream>> GetFeaturedStreamsAsync(TwitchPageOptions options = null); Task<IEnumerable<IStreamSummary>> GetStreamSummaryAsync(string game); Task<IEnumerable<ITeamInfo>> GetTeamsAsync(TwitchPageOptions options = null); Task<IEnumerable<ITeam>> GetTeamAsync(string name); Task<IUser> GetUserAsync(ulong id); } } ``` Add missing Async name to GetTopGames
```c# using System.Collections.Generic; using System.Threading.Tasks; namespace NTwitch { public interface ITwitchClient { ConnectionState ConnectionState { get; } Task<IChannel> GetChannelAsync(ulong id); Task<IEnumerable<ITopGame>> GetTopGamesAsync(TwitchPageOptions options = null); Task<IEnumerable<IIngest>> GetIngestsAsync(); Task<IEnumerable<IChannel>> FindChannelsAsync(string query, TwitchPageOptions options = null); Task<IEnumerable<IGame>> FindGamesAsync(string query, bool islive = true); Task<IStream> GetStreamAsync(ulong id, StreamType type = StreamType.All); Task<IEnumerable<IStream>> FindStreamsAsync(string query, bool hls = true, TwitchPageOptions options = null); Task<IEnumerable<IStream>> GetStreamsAsync(string game = null, ulong[] channelids = null, string language = null, StreamType type = StreamType.All, TwitchPageOptions options = null); Task<IEnumerable<IFeaturedStream>> GetFeaturedStreamsAsync(TwitchPageOptions options = null); Task<IEnumerable<IStreamSummary>> GetStreamSummaryAsync(string game); Task<IEnumerable<ITeamInfo>> GetTeamsAsync(TwitchPageOptions options = null); Task<IEnumerable<ITeam>> GetTeamAsync(string name); Task<IUser> GetUserAsync(ulong id); } } ```
bf23425d-f42a-4fce-9635-0876c30a1e47
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; namespace Microsoft.Its.Domain { /// <summary> /// Provides access to system time. /// </summary> [DebuggerStepThrough] public class SystemClock : IClock { public static readonly SystemClock Instance = new SystemClock(); private SystemClock() { } /// <summary> /// Gets the current time via <see cref="DateTimeOffset.Now" />. /// </summary> public DateTimeOffset Now() { return DateTimeOffset.Now; } public override string ToString() { return GetType() + ": " + Now().ToString("O"); } } } ``` Update the systemclock to use UtcNow. This is because some of code use Month, Year properties of DateTimeOffset
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; namespace Microsoft.Its.Domain { /// <summary> /// Provides access to system time. /// </summary> [DebuggerStepThrough] public class SystemClock : IClock { public static readonly SystemClock Instance = new SystemClock(); private SystemClock() { } /// <summary> /// Gets the current time via <see cref="DateTimeOffset.Now" />. /// </summary> public DateTimeOffset Now() { return DateTimeOffset.UtcNow; } public override string ToString() { return GetType() + ": " + Now().ToString("O"); } } } ```
f32b8299-7035-45e5-8915-79a5aa9954fd
{ "language": "C#" }
```c# @model string @{ ViewData["Title"] = "Thank you"; ViewData["og:title"] = "Thank you"; Layout = "../Shared/_Layout.cshtml"; } <div class="grid-container-full-width"> <div class="grid-container grid-100"> <div class="l-body-section-filled l-short-content mobile-grid-100 tablet-grid-100 grid-100"> <section aria-label="Thank you message" class="grid-100 mobile-grid-100"> <div class="l-content-container l-article-container"> <h1>Thank you for contacting us</h1> <p>We will aim to respond to your enquiry within 10 working days.</p> <stock-button href="@Model">Return to previous page</stock-button> </div> </section> </div> </div> </div> ``` Revert "Gary changed wording per content request"
```c# @model string @{ ViewData["Title"] = "Thank you"; ViewData["og:title"] = "Thank you"; Layout = "../Shared/_Layout.cshtml"; } <div class="grid-container-full-width"> <div class="grid-container grid-100"> <div class="l-body-section-filled l-short-content mobile-grid-100 tablet-grid-100 grid-100"> <section aria-label="Thank you message" class="grid-100 mobile-grid-100"> <div class="l-content-container l-article-container"> <h1>Thank you for contacting us</h1> <p>We will endeavour to respond to your enquiry within 10 working days.</p> <stock-button href="@Model">Return To Previous Page</stock-button> </div> </section> </div> </div> </div> ```
565bbc08-945d-4b02-bbcb-e78197b0da23
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Net.Mail; using SendGrid; using TapBoxCommon.Models; using Microsoft.Azure; namespace TapBoxWebjob { class MailSender { public static void SendMailToOwner(Device NotifierDevice, int SensorValue) { SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(NotifierDevice.OwnerMailAddress); myMessage.From = new MailAddress("sjost@hsr.ch", "Samuel Jost"); myMessage.Subject = "Notification from your Tapbox"; Console.WriteLine($"Device: {NotifierDevice.DeviceName} - Sensor Value: {SensorValue}"); if (SensorValue < 20) { Console.WriteLine("Your Mailbox is Empty"); return; } else if (SensorValue < 300) { Console.WriteLine("You have some Mail"); myMessage.Text = "You have some Mail in your device "+NotifierDevice.DeviceName; } else if (SensorValue > 300) { Console.WriteLine("You have A Lot of Mail"); myMessage.Text = "You have a lot of Mail in your device " + NotifierDevice.DeviceName; } var apiKey = CloudConfigurationManager.GetSetting("SendGrid.API_Key"); var transportWeb = new Web(apiKey); // Send the email, which returns an awaitable task. transportWeb.DeliverAsync(myMessage); } } } ``` Change Sensor level to 100
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Net.Mail; using SendGrid; using TapBoxCommon.Models; using Microsoft.Azure; namespace TapBoxWebjob { class MailSender { public static void SendMailToOwner(Device NotifierDevice, int SensorValue) { SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(NotifierDevice.OwnerMailAddress); myMessage.From = new MailAddress("sjost@hsr.ch", "Samuel Jost"); myMessage.Subject = "Notification from your Tapbox"; Console.WriteLine($"Device: {NotifierDevice.DeviceName} - Sensor Value: {SensorValue}"); if (SensorValue < 100) { Console.WriteLine("Your Mailbox is Empty"); return; } else if (SensorValue < 300) { Console.WriteLine("You have some Mail"); myMessage.Text = "You have some Mail in your device "+NotifierDevice.DeviceName; } else if (SensorValue > 300) { Console.WriteLine("You have A Lot of Mail"); myMessage.Text = "You have a lot of Mail in your device " + NotifierDevice.DeviceName; } var apiKey = CloudConfigurationManager.GetSetting("SendGrid.API_Key"); var transportWeb = new Web(apiKey); // Send the email, which returns an awaitable task. transportWeb.DeliverAsync(myMessage); } } } ```
61d68354-931c-4c75-b934-53ad81a4d41c
{ "language": "C#" }
```c# using System; namespace Csla { internal class BrowsableAttribute : Attribute { public BrowsableAttribute(bool flag) { } } internal class DisplayAttribute : Attribute { public string Name { get; set; } public bool AutoGenerateField { get; set; } public DisplayAttribute(bool AutoGenerateField = false, string Name = "") { this.AutoGenerateField = AutoGenerateField; this.Name = Name; } } } ``` Add missing comment block. bugid: 812
```c# //----------------------------------------------------------------------- // <copyright file="PortedAttributes.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Dummy implementations of .NET attributes missing in WP7.</summary> //----------------------------------------------------------------------- using System; namespace Csla { internal class BrowsableAttribute : Attribute { public BrowsableAttribute(bool flag) { } } internal class DisplayAttribute : Attribute { public string Name { get; set; } public bool AutoGenerateField { get; set; } public DisplayAttribute(bool AutoGenerateField = false, string Name = "") { this.AutoGenerateField = AutoGenerateField; this.Name = Name; } } } ```
60608398-d14e-4127-85db-0672eef2ef5c
{ "language": "C#" }
```c# using System; using FeatureSwitcher.AwsConfiguration.Behaviours; namespace FeatureSwitcher.AwsConfiguration.Models { internal class BehaviourCacheItem { public IBehaviour Behaviour { get; } public DateTime CacheTimeout { get; } public bool IsExpired => this.CacheTimeout < DateTime.UtcNow; public BehaviourCacheItem(IBehaviour behaviour, TimeSpan cacheTime) { Behaviour = behaviour; CacheTimeout = DateTime.UtcNow.Add(cacheTime); } public void ExtendCache() { CacheTimeout.Add(TimeSpan.FromMinutes(1)); } } } ``` Fix bug: Ensure CacheTimeout is actually set when extending cache.
```c# using System; using FeatureSwitcher.AwsConfiguration.Behaviours; namespace FeatureSwitcher.AwsConfiguration.Models { internal class BehaviourCacheItem { public IBehaviour Behaviour { get; } public DateTime CacheTimeout { get; private set; } public bool IsExpired => this.CacheTimeout < DateTime.UtcNow; public BehaviourCacheItem(IBehaviour behaviour, TimeSpan cacheTime) { Behaviour = behaviour; CacheTimeout = DateTime.UtcNow.Add(cacheTime); } public void ExtendCache() { CacheTimeout = CacheTimeout.Add(TimeSpan.FromMinutes(1)); } } } ```
1b3d5fcd-cd75-475d-9cb8-b6754f0d0879
{ "language": "C#" }
```c# using TruckRouter.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseDeveloperExceptionPage(); } else { app.UseHttpsRedirection(); app.UseAuthorization(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); ``` Remove code that unconditionally enable https redirects and authorization
```c# using TruckRouter.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseDeveloperExceptionPage(); } else { app.UseHttpsRedirection(); app.UseAuthorization(); } app.MapControllers(); app.Run(); ```
3cc7cabd-0818-4257-a3c8-8a05fe761bd5
{ "language": "C#" }
```c# using NLog; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace SyncTrayzor.Syncthing.ApiClient { public class SyncthingHttpClientHandler : WebRequestHandler { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public SyncthingHttpClientHandler() { // We expect Syncthing to return invalid certs this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); if (response.IsSuccessStatusCode) logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim()); else logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim()); return response; } } } ``` Add logging in case of null response from Syncthing
```c# using NLog; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace SyncTrayzor.Syncthing.ApiClient { public class SyncthingHttpClientHandler : WebRequestHandler { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public SyncthingHttpClientHandler() { // We expect Syncthing to return invalid certs this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); // We're getting null bodies from somewhere: try and figure out where var responseString = await response.Content.ReadAsStringAsync(); if (responseString == null) logger.Warn($"Null response received from {request.RequestUri}. {response}. Content (again): {response.Content.ReadAsStringAsync()}"); if (response.IsSuccessStatusCode) logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim()); else logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim()); return response; } } } ```
64823092-6e16-4e1d-b545-0779c9437e0d
{ "language": "C#" }
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Reflection; using Microsoft.Common.Core; using Microsoft.R.Host.Protocol; namespace Microsoft.R.Host.Client { public static class AboutHostExtensions { private static Version _localVersion; static AboutHostExtensions() { _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version; } public static string IsHostVersionCompatible(this AboutHost aboutHost) { if (_localVersion.Major != 0 || _localVersion.Minor != 0) { // Filter out debug builds var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor); var clientVersion = new Version(_localVersion.Major, _localVersion.Minor); if (serverVersion > clientVersion) { return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion); } if (serverVersion < clientVersion) { return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion); } } return null; } } }``` Allow debug mode to connect to any version of remote.
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Reflection; using Microsoft.Common.Core; using Microsoft.R.Host.Protocol; namespace Microsoft.R.Host.Client { public static class AboutHostExtensions { private static Version _localVersion; static AboutHostExtensions() { _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version; } public static string IsHostVersionCompatible(this AboutHost aboutHost) { #if !DEBUG if (_localVersion.Major != 0 || _localVersion.Minor != 0) { // Filter out debug builds var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor); var clientVersion = new Version(_localVersion.Major, _localVersion.Minor); if (serverVersion > clientVersion) { return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion); } if (serverVersion < clientVersion) { return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion); } } #endif return null; } } }```
e81ff7dd-b0a0-4a62-958e-6ee8d625925e
{ "language": "C#" }
```c# using System.Runtime.Remoting.Channels; namespace RedGate.AppHost.Remoting { internal class ClientChannelSinkProviderForParticularServer : IClientChannelSinkProvider { private readonly IClientChannelSinkProvider m_Upstream; private readonly string m_Url; internal ClientChannelSinkProviderForParticularServer(IClientChannelSinkProvider upstream, string id) { if (upstream == null) throw new ArgumentNullException("upstream"); if (String.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); m_Upstream = upstream; m_Url = string.Format("ipc://{0}", id); } public IClientChannelSinkProvider Next { get { return m_Upstream.Next; } set { m_Upstream.Next = value; } } public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData) { return url == m_Url ? m_Upstream.CreateSink(channel, url, remoteChannelData) : null; } } }``` Document why null is ok here
```c# using System; using System.Runtime.Remoting.Channels; namespace RedGate.AppHost.Remoting { internal class ClientChannelSinkProviderForParticularServer : IClientChannelSinkProvider { private readonly IClientChannelSinkProvider m_Upstream; private readonly string m_Url; internal ClientChannelSinkProviderForParticularServer(IClientChannelSinkProvider upstream, string id) { if (upstream == null) throw new ArgumentNullException("upstream"); if (String.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); m_Upstream = upstream; m_Url = string.Format("ipc://{0}", id); } public IClientChannelSinkProvider Next { get { return m_Upstream.Next; } set { m_Upstream.Next = value; } } public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData) { //Returning null indicates that the sink cannot be created as per Microsoft documentation return url == m_Url ? m_Upstream.CreateSink(channel, url, remoteChannelData) : null; } } }```