doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
d9862d65-6509-4973-a53a-7efaa11bb662
{ "language": "C#" }
```c# using System; using System.IO; using System.Reflection; using NServiceBus; using NServiceBus.Settings; static class ScriptLocation { public static string FindScriptDirectory(ReadOnlySettings settings) { var currentDirectory = GetCurrentDirectory(settings); return Path.Combine(currentDirectory, "NServiceBus.Persistence.Sql", settings.GetSqlDialect().Name); } static string GetCurrentDirectory(ReadOnlySettings settings) { if (settings.TryGet("SqlPersistence.ScriptDirectory", out string scriptDirectory)) { return scriptDirectory; } var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) { return AppDomain.CurrentDomain.BaseDirectory; } var codeBase = entryAssembly.CodeBase; return Directory.GetParent(new Uri(codeBase).LocalPath).FullName; } public static void ValidateScriptExists(string createScript) { if (!File.Exists(createScript)) { throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint or NServiceBus.Persistence.Sql.MsBuild nuget was not included in the project."); } } }``` Fix script location via AppDomain base dir for web applications
```c# using System; using System.IO; using System.Reflection; using NServiceBus; using NServiceBus.Settings; static class ScriptLocation { const string ScriptFolder = "NServiceBus.Persistence.Sql"; public static string FindScriptDirectory(ReadOnlySettings settings) { var currentDirectory = GetCurrentDirectory(settings); return Path.Combine(currentDirectory, ScriptFolder, settings.GetSqlDialect().Name); } static string GetCurrentDirectory(ReadOnlySettings settings) { if (settings.TryGet("SqlPersistence.ScriptDirectory", out string scriptDirectory)) { return scriptDirectory; } var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) { var baseDir = AppDomain.CurrentDomain.BaseDirectory; var scriptDir = Path.Combine(baseDir, ScriptFolder); //if the app domain base dir contains the scripts folder, return it. Otherwise add "bin" to the base dir so that web apps work correctly if (Directory.Exists(scriptDir)) { return baseDir; } return Path.Combine(baseDir, "bin"); } var codeBase = entryAssembly.CodeBase; return Directory.GetParent(new Uri(codeBase).LocalPath).FullName; } public static void ValidateScriptExists(string createScript) { if (!File.Exists(createScript)) { throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint or NServiceBus.Persistence.Sql.MsBuild nuget was not included in the project."); } } }```
c32ffcbc-e168-40fd-a931-b8f9011e2732
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Rhaeo.Mvvm { public class ObservableObject { } }``` Implement extracting the property name
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="ObservableObject.cs" company="Rhaeo"> // Licenced under the MIT licence. // </copyright> // <summary> // Defines the ObservableObject type. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Linq.Expressions; namespace Rhaeo.Mvvm { /// <summary> /// Serves as a back class for object instances obserable through the <see cref="INotifyPropertyChanged"/> interface. /// </summary> public class ObservableObject : INotifyPropertyChanged { #region Events /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Methods /// <summary> /// Raises the <see cref="PropertyChanged"/> event with a property name extracted from the property expression. /// </summary> /// <typeparam name="TViewModel"> /// The view model type. /// </typeparam> /// <typeparam name="TValue"> /// The property value type. /// </typeparam> /// <param name="propertyExpression"> /// The property expression. /// </param> protected void RaisePropertyChanged<TViewModel, TValue>(Expression<Func<TViewModel, TValue>> propertyExpression) where TViewModel : ObservableObject { var propertyName = (propertyExpression.Body as MemberExpression).Member.Name; var propertyChangedHandler = this.PropertyChanged; if (propertyChangedHandler != null) { propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }```
99a5f6af-e169-41f2-a0d9-b67c5135eab4
{ "language": "C#" }
```c# // https://www.reddit.com/r/dailyprogrammer/comments/3n55f3/20150930_challenge_234_intermediate_red_squiggles/ // // Your challenge today is to implement a real time spell checker and indicate where you would throw the red squiggle. For your dictionary use /usr/share/dict/words // using System; using System.Collections.Generic; using System.IO; using System.Linq; class Trie { private class Node { internal Dictionary<char, Node> Next = new Dictionary<char, Node>(); bool IsWord = false; } } class Program { static void Main() { Trie trie = new Trie(); using (StreamReader reader = new StreamReader("/usr/share/dict/words")) { String line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } } ``` Build and print the trie
```c# // https://www.reddit.com/r/dailyprogrammer/comments/3n55f3/20150930_challenge_234_intermediate_red_squiggles/ // // Your challenge today is to implement a real time spell checker and indicate where you would throw the red squiggle. For your dictionary use /usr/share/dict/words // using System; using System.Collections.Generic; using System.IO; using System.Linq; class Trie { private class Node { internal Dictionary<char, Node> Next = new Dictionary<char, Node>(); internal bool IsWord = false; public override String ToString() { return String.Format("[Node.IsWord:{0} {1}]", IsWord, String.Join(", ", Next.Select(x => String.Format("{0} => {1}", x.Key, x.Value.ToString())))); } } private readonly Node Root = new Node(); public void Add(String s) { Node current = Root; for (int i = 0; i < s.Length; i++) { Node next; if (!current.Next.TryGetValue(s[i], out next)) { next = new Node(); current.Next[s[i]] = next; } next.IsWord = i == s.Length - 1; current = next; } } public override String ToString() { return Root.ToString(); } } class Program { static void Main() { Trie trie = new Trie(); using (StreamReader reader = new StreamReader("/usr/share/dict/words")) { String line; while ((line = reader.ReadLine()) != null) { trie.Add(line); } } Console.WriteLine(trie); } } ```
9421d5dc-55bd-4e1b-99e5-b90bf91c72ef
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; namespace SampleGame.Android { [Activity(Label = "SampleGame", MainLauncher = true, ScreenOrientation = ScreenOrientation.Landscape, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(new SampleGameView(this)); } } } ``` Allow rotating the screen without crashing by overriding the Configuration changes.
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; using System; using Android.Runtime; using Android.Content.Res; namespace SampleGame.Android { [Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { private SampleGameView sampleGameView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(sampleGameView = new SampleGameView(this)); } } } ```
96808a15-4893-4cfe-9270-cd9734dd808f
{ "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("PinWin")] [assembly: AssemblyDescription("Allows user to make desktop windows top most")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PinWin")] [assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.4")] [assembly: AssemblyFileVersion("0.2.4")] ``` Increment version before creating release (0.2.5).
```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("PinWin")] [assembly: AssemblyDescription("Allows user to make desktop windows top most")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PinWin")] [assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.5")] [assembly: AssemblyFileVersion("0.2.5")] ```
9c12c34b-c46e-47d4-8f9a-5c1fb0a95f5b
{ "language": "C#" }
```c# // Copyright (c) 2016-2017 Nicolas Musset. All rights reserved. // This file is licensed under the MIT license. // See the LICENSE.md file in the project root for more information. using System; using System.Windows.Documents; using Markdig.Annotations; using Markdig.Syntax.Inlines; using Markdig.Wpf; namespace Markdig.Renderers.Wpf.Inlines { /// <summary> /// A WPF renderer for a <see cref="AutolinkInline"/>. /// </summary> /// <seealso cref="Markdig.Renderers.Wpf.WpfObjectRenderer{Markdig.Syntax.Inlines.AutolinkInline}" /> public class AutolinkInlineRenderer : WpfObjectRenderer<AutolinkInline> { /// <inheritdoc/> protected override void Write([NotNull] WpfRenderer renderer, [NotNull] AutolinkInline link) { var url = link.Url; if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) { url = "#"; } var hyperlink = new Hyperlink { Command = Commands.Hyperlink, CommandParameter = url, NavigateUri = new Uri(url, UriKind.RelativeOrAbsolute), ToolTip = url, }; renderer.WriteInline(hyperlink); } } } ``` Write the autolink's URL so we can see the autolink.
```c# // Copyright (c) 2016-2017 Nicolas Musset. All rights reserved. // This file is licensed under the MIT license. // See the LICENSE.md file in the project root for more information. using System; using System.Windows.Documents; using Markdig.Annotations; using Markdig.Syntax.Inlines; using Markdig.Wpf; namespace Markdig.Renderers.Wpf.Inlines { /// <summary> /// A WPF renderer for a <see cref="AutolinkInline"/>. /// </summary> /// <seealso cref="Markdig.Renderers.Wpf.WpfObjectRenderer{Markdig.Syntax.Inlines.AutolinkInline}" /> public class AutolinkInlineRenderer : WpfObjectRenderer<AutolinkInline> { /// <inheritdoc/> protected override void Write([NotNull] WpfRenderer renderer, [NotNull] AutolinkInline link) { var url = link.Url; if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) { url = "#"; } var hyperlink = new Hyperlink { Command = Commands.Hyperlink, CommandParameter = url, NavigateUri = new Uri(url, UriKind.RelativeOrAbsolute), ToolTip = url, }; renderer.Push(hyperlink); renderer.WriteText(link.Url); renderer.Pop(); } } } ```
27c3ab60-50ca-49f2-8cd7-21188be5b6b5
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Swashbuckle.Swagger.Application { public class SwaggerSerializerFactory { internal static JsonSerializer Create(IOptions<MvcJsonOptions> mvcJsonOptions) { // TODO: Should this handle case where mvcJsonOptions.Value == null? return new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new SwaggerContractResolver(mvcJsonOptions.Value.SerializerSettings) }; } } } ``` Use MvcJsonOptions json serializer formatting when generating swagger.json
```c# using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Swashbuckle.Swagger.Application { public class SwaggerSerializerFactory { internal static JsonSerializer Create(IOptions<MvcJsonOptions> mvcJsonOptions) { // TODO: Should this handle case where mvcJsonOptions.Value == null? return new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, Formatting = mvcJsonOptions.Value.SerializerSettings.Formatting, ContractResolver = new SwaggerContractResolver(mvcJsonOptions.Value.SerializerSettings) }; } } } ```
ce24d6f1-9e81-431b-aa40-7530b958e2b8
{ "language": "C#" }
```c# using Ninject; using Ninject.Modules; using Ninject.Web.Common; using Raven.Client; using Raven.Client.Embedded; namespace CGO.Web.NinjectModules { public class RavenModule : NinjectModule { public override void Load() { Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope(); Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope(); } private static IDocumentStore InitialiseDocumentStore() { var documentStore = new EmbeddableDocumentStore { DataDirectory = "CGO.raven", UseEmbeddedHttpServer = true, Configuration = { Port = 28645 } }; documentStore.Initialize(); documentStore.InitializeProfiling(); return documentStore; } } }``` Disable Raven's Embedded HTTP server
```c# using Ninject; using Ninject.Modules; using Ninject.Web.Common; using Raven.Client; using Raven.Client.Embedded; namespace CGO.Web.NinjectModules { public class RavenModule : NinjectModule { public override void Load() { Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope(); Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope(); } private static IDocumentStore InitialiseDocumentStore() { var documentStore = new EmbeddableDocumentStore { DataDirectory = "CGO.raven", Configuration = { Port = 28645 } }; documentStore.Initialize(); documentStore.InitializeProfiling(); return documentStore; } } }```
b53effa8-cada-4b8a-88cd-1a1f6b7524cc
{ "language": "C#" }
```c# using Conventional.Conventions; namespace Pirac.Conventions { internal class ViewConvention : Convention { public ViewConvention() { Must.HaveNameEndWith("View").BeAClass(); Should.BeAConcreteClass(); BaseName = t => t.Name.Substring(0, t.Name.Length - 4); Variants.HaveBaseNameAndEndWith("View"); } } }``` Update View convention to recognize MainWindow
```c# using System; using Conventional.Conventions; namespace Pirac.Conventions { internal class ViewConvention : Convention { public ViewConvention() { Must.Pass(t => t.IsClass && (t.Name.EndsWith("View") || t.Name == "MainWindow"), "Name ends with View or is named MainWindow"); Should.BeAConcreteClass(); BaseName = t => t.Name == "MainWindow" ? t.Name : t.Name.Substring(0, t.Name.Length - 4); Variants.Add(new DelegateBaseFilter((t, b) => { if (t.Name == "MainWindow" && b == "MainWindow") return true; return t.Name == b + "View"; })); } class DelegateBaseFilter : IBaseFilter { private readonly Func<Type, string, bool> predicate; public DelegateBaseFilter(Func<Type, string, bool> predicate) { this.predicate = predicate; } public bool Matches(Type t, string baseName) { return predicate(t, baseName); } } } }```
e725301f-ba51-4c69-8114-f6eb1adc2c0b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using Cake.Core; using Cake.Core.Configuration; using Cake.Frosting; using Cake.NuGet; public class Program : IFrostingStartup { public static int Main(string[] args) { // Create the host. var host = new CakeHostBuilder() .WithArguments(args) .UseStartup<Program>() .Build(); // Run the host. return host.Run(); } public void Configure(ICakeServices services) { services.UseContext<Context>(); services.UseLifetime<Lifetime>(); services.UseWorkingDirectory(".."); // from https://github.com/cake-build/cake/discussions/2931 var module = new NuGetModule(new CakeConfiguration(new Dictionary<string, string>())); module.Register(services); services.UseTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1")); services.UseTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0")); services.UseTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0")); } } ``` Install NuGet as a tool
```c# using System; using System.Collections.Generic; using System.IO; using Cake.Core; using Cake.Core.Configuration; using Cake.Frosting; using Cake.NuGet; public class Program : IFrostingStartup { public static int Main(string[] args) { // Create the host. var host = new CakeHostBuilder() .WithArguments(args) .UseStartup<Program>() .Build(); // Run the host. return host.Run(); } public void Configure(ICakeServices services) { services.UseContext<Context>(); services.UseLifetime<Lifetime>(); services.UseWorkingDirectory(".."); // from https://github.com/cake-build/cake/discussions/2931 var module = new NuGetModule(new CakeConfiguration(new Dictionary<string, string>())); module.Register(services); services.UseTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1")); services.UseTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0")); services.UseTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0")); services.UseTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0")); } } ```
78665c1c-d05a-4df3-8d39-fe68a77ca3af
{ "language": "C#" }
```c# /* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using QuantConnect.Configuration; namespace QuantConnect { /// <summary> /// Provides application level constant values /// </summary> public static class Constants { /// <summary> /// The root directory of the data folder for this application /// </summary> public static string DataFolder { get { return Config.Get("data-folder", @"../../../Data/"); } } /// <summary> /// The directory used for storing downloaded remote files /// </summary> public const string Cache = "./cache/data"; /// <summary> /// The version of lean /// </summary> public static readonly string Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } ``` Move DataFolder config get to static member initializer
```c# /* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using QuantConnect.Configuration; namespace QuantConnect { /// <summary> /// Provides application level constant values /// </summary> public static class Constants { private static readonly string DataFolderPath = Config.Get("data-folder", @"../../../Data/"); /// <summary> /// The root directory of the data folder for this application /// </summary> public static string DataFolder { get { return DataFolderPath; } } /// <summary> /// The directory used for storing downloaded remote files /// </summary> public const string Cache = "./cache/data"; /// <summary> /// The version of lean /// </summary> public static readonly string Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } ```
2ff18159-a1a4-419c-a42c-c24e3aa21a5e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Kyru.Core { class Config { internal readonly string storeDirectory; internal Config() { storeDirectory = Path.Combine(System.Windows.Forms.Application.UserAppDataPath); } } } ``` Use a path for storage that doesn't include version and company name
```c# using System; using System.IO; namespace Kyru.Core { internal sealed class Config { internal string storeDirectory; internal Config() { storeDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Kyru", "objects"); } } }```
432b5494-c2b7-4dcd-9a58-298a18d34054
{ "language": "C#" }
```c# using System; using System.IO; using Mango; // // This the default StaticContentModule that comes with all Mango apps // if you do not wish to serve any static content with Mango you can // remove its route handler from <YourApp>.cs's constructor and delete // this file. // // All Content placed on the Content/ folder should be handled by this // module. // namespace $APPNAME { public class StaticContentModule : MangoModule { public StaticContentModule () { Get ("*", Content); } public static void Content (MangoContext ctx) { string path = ctx.Request.LocalPath; if (path.StartsWith ("/")) path = path.Substring (1); if (File.Exists (path)) { ctx.Response.SendFile (path); } else ctx.Response.StatusCode = 404; } } } ``` Update the static content module to fit the new API.
```c# using System; using System.IO; using Mango; // // This the default StaticContentModule that comes with all Mango apps // if you do not wish to serve any static content with Mango you can // remove its route handler from <YourApp>.cs's constructor and delete // this file. // // All Content placed on the Content/ folder should be handled by this // module. // namespace AppNameFoo { public class StaticContentModule : MangoModule { public StaticContentModule () { Get ("*", Content); } public static void Content (IMangoContext ctx) { string path = ctx.Request.LocalPath; if (path.StartsWith ("/")) path = path.Substring (1); if (File.Exists (path)) { ctx.Response.SendFile (path); } else ctx.Response.StatusCode = 404; } } } ```
5a64561d-8cc0-4e95-8e39-29afe6208c2c
{ "language": "C#" }
```c# using System; using Mono.Addins; using Mono.Addins.Description; [assembly:Addin ( "${ProjectName}", Namespace = "${ProjectName}", Version = "1.0" )] [assembly:AddinName ("${ProjectName}")] [assembly:AddinCategory ("${ProjectName}")] [assembly:AddinDescription ("${ProjectName}")] [assembly:AddinAuthor ("${AuthorName}")]``` Fix default category for new addins
```c# using System; using Mono.Addins; using Mono.Addins.Description; [assembly:Addin ( "${ProjectName}", Namespace = "${ProjectName}", Version = "1.0" )] [assembly:AddinName ("${ProjectName}")] [assembly:AddinCategory ("IDE extensions")] [assembly:AddinDescription ("${ProjectName}")] [assembly:AddinAuthor ("${AuthorName}")] ```
e85fc94d-0483-41f4-b610-c78cb8a420a0
{ "language": "C#" }
```c# using Nancy; using Owin; namespace Bbl.KnockoutJs { public class Startup { public void Configuration(IAppBuilder app) { app.UseNancy(); } } public class IndexModule : NancyModule { public IndexModule() { Get["/"] = parameters => View["index"]; } } }``` Add url to get unicorns
```c# using System.IO; using System.Linq; using System.Web.Hosting; using Nancy; using Owin; namespace Bbl.KnockoutJs { public class Startup { public void Configuration(IAppBuilder app) { app.UseNancy(); } } public class IndexModule : NancyModule { private const string UnicornsPath = "/Content/Unicorn/"; public IndexModule() { Get["/"] = parameters => View["index"]; Get["/api/unicorns"] = parameters => { var imagesDirectory = HostingEnvironment.MapPath("~" + UnicornsPath); return new DirectoryInfo(imagesDirectory) .EnumerateFiles() .Select(ConvertToDto); }; } private dynamic ConvertToDto(FileInfo file) { var name = Path.GetFileNameWithoutExtension(file.Name); return new { Key = name, ImagePath = UnicornsPath + file.Name, Name = name.Replace('_', ' '), Keywords = name.Split('_'), CreationDate = file.CreationTime }; } } }```
1bc70bcc-a769-4a8c-bf46-5c96dd8bd9d8
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.IO; namespace dotnet_new2 { public class ProjectCreator { public bool CreateProject(string name, string path, Template template) { Directory.CreateDirectory(path); foreach (var file in template.Files) { var dest = Path.Combine(path, file.DestPath); File.Copy(file.SourcePath, dest); ProcessFile(dest, name); } Console.WriteLine(); Console.WriteLine($"Created \"{name}\" in {path}"); return true; } private void ProcessFile(string destPath, string name) { // TODO: Make this good var contents = File.ReadAllText(destPath); File.WriteAllText(destPath, contents.Replace("$DefaultNamespace$", name)); } } }``` Fix case when project directory already exists
```c# using System; using System.Diagnostics; using System.IO; namespace dotnet_new2 { public class ProjectCreator { public bool CreateProject(string name, string path, Template template) { Directory.CreateDirectory(path); if (Directory.GetFileSystemEntries(path).Length > 0) { // Files already exist in the directory Console.WriteLine($"Directory {path} already contains files. Please specify a different project name."); return false; } foreach (var file in template.Files) { var dest = Path.Combine(path, file.DestPath); File.Copy(file.SourcePath, dest); ProcessFile(dest, name); } Console.WriteLine(); Console.WriteLine($"Created \"{name}\" in {path}"); Console.WriteLine(); return true; } private void ProcessFile(string destPath, string name) { // TODO: Make this good var contents = File.ReadAllText(destPath); File.WriteAllText(destPath, contents.Replace("$DefaultNamespace$", name)); } } }```
b035d27a-2aa6-4e97-b262-da7d330ffafa
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace SteamIrcBot { class ServiceDispatcher { static ServiceDispatcher _instance = new ServiceDispatcher(); public static ServiceDispatcher Instance { get { return _instance; } } Task dispatcher; CancellationTokenSource cancelToken; ServiceDispatcher() { cancelToken = new CancellationTokenSource(); dispatcher = new Task( ServiceTick, cancelToken.Token, TaskCreationOptions.LongRunning ); } void ServiceTick() { while ( true ) { if ( cancelToken.IsCancellationRequested ) break; Steam.Instance.Tick(); IRC.Instance.Tick(); RSS.Instance.Tick(); } } public void Start() { dispatcher.Start(); } public void Stop() { cancelToken.Cancel(); } public void Wait() { try { dispatcher.Wait(); } catch ( AggregateException ) { // we'll ignore any cancelled/failed tasks } } } } ``` Throw all dispatcher exceptions on the non-service build.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace SteamIrcBot { class ServiceDispatcher { static ServiceDispatcher _instance = new ServiceDispatcher(); public static ServiceDispatcher Instance { get { return _instance; } } Task dispatcher; CancellationTokenSource cancelToken; ServiceDispatcher() { cancelToken = new CancellationTokenSource(); dispatcher = new Task( ServiceTick, cancelToken.Token, TaskCreationOptions.LongRunning ); } void ServiceTick() { while ( true ) { if ( cancelToken.IsCancellationRequested ) break; Steam.Instance.Tick(); IRC.Instance.Tick(); RSS.Instance.Tick(); } } public void Start() { dispatcher.Start(); } public void Stop() { cancelToken.Cancel(); } public void Wait() { dispatcher.Wait(); } } } ```
f8dfaed9-9dfe-431e-a53c-f3d6ff2e9246
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace Monacs.Core.Unit { ///<summary> /// Extensions for <see cref="Result<Unit>" /> type. ///</summary> public static class Result { ///<summary> /// Creates successful <see cref="Result<Unit>" />. ///</summary> public static Result<Unit> Ok() => Core.Result.Ok(Unit.Default); ///<summary> /// Creates failed <see cref="Result<Unit>" /> with provided error details. ///</summary> public static Result<Unit> Error(ErrorDetails error) => Core.Result.Error<Unit>(error); ///<summary> /// Rejects the value of the <see cref="Result<T>" /> and returns <see cref="Result<Unit>" /> instead. /// If the input <see cref="Result<T>" /> is Error then the error details are preserved. ///</summary> public static Result<Unit> Ignore<T>(this Result<T> result) => result.Map(_ => Unit.Default); } } ``` Fix the XML docs generic class references
```c# using System; using System.Collections.Generic; using System.Linq; namespace Monacs.Core.Unit { ///<summary> /// Extensions for <see cref="Result{Unit}" /> type. ///</summary> public static class Result { ///<summary> /// Creates successful <see cref="Result{Unit}" />. ///</summary> public static Result<Unit> Ok() => Core.Result.Ok(Unit.Default); ///<summary> /// Creates failed <see cref="Result{Unit}" /> with provided error details. ///</summary> public static Result<Unit> Error(ErrorDetails error) => Core.Result.Error<Unit>(error); ///<summary> /// Rejects the value of the <see cref="Result{T}" /> and returns <see cref="Result{Unit}" /> instead. /// If the input <see cref="Result{T}" /> is Error then the error details are preserved. ///</summary> public static Result<Unit> Ignore<T>(this Result<T> result) => result.Map(_ => Unit.Default); } } ```
1918f7be-31e4-450d-b533-d475a0a27c29
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ProviderModel")] [assembly: AssemblyDescription("An improvment over the bundled .NET provider model")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Enrique Alejandro Allegretta")] [assembly: AssemblyProduct("ProviderModel")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("en-US")] [assembly: ComVisible(false)] [assembly: Guid("9d02304c-cda1-4d3b-afbc-725731a794b5")] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] ``` Set assembly culture to neutral
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ProviderModel")] [assembly: AssemblyDescription("An improvment over the bundled .NET provider model")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Enrique Alejandro Allegretta")] [assembly: AssemblyProduct("ProviderModel")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("9d02304c-cda1-4d3b-afbc-725731a794b5")] [assembly: AssemblyVersion("1.0.1")] [assembly: AssemblyFileVersion("1.0.1")] [assembly: AssemblyInformationalVersion("1.0.1")] ```
ef209820-f8c1-4205-8e48-ed653a8c12bc
{ "language": "C#" }
```c# using SOVND.Lib; using System.IO; namespace SOVND.Server { public class ServerMqttSettings : IMQTTSettings { public string Broker { get { return "104.131.87.42"; } } public int Port { get { return 8883; } } public string Username { get { return File.ReadAllText("username.key"); } } public string Password { get { return File.ReadAllText("password.key"); } } } }``` Change port for new RabbitMQ-MQTT server
```c# using SOVND.Lib; using System.IO; namespace SOVND.Server { public class ServerMqttSettings : IMQTTSettings { public string Broker { get { return "104.131.87.42"; } } public int Port { get { return 2883; } } public string Username { get { return File.ReadAllText("username.key"); } } public string Password { get { return File.ReadAllText("password.key"); } } } }```
ec8ab3d1-320d-431b-8929-bc1e398787af
{ "language": "C#" }
```c# using System; using System.IO; using GLib; using Hyena; using TagLib.Image; using TagLib.Xmp; namespace FSpot.Utils { public static class SidecarXmpExtensions { /// <summary> /// Parses the XMP file identified by resource and replaces the XMP /// tag of file by the parsed data. /// </summary> public static void ParseXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource) { string xmp; using (var stream = resource.ReadStream) { using (var reader = new StreamReader (stream)) { xmp = reader.ReadToEnd (); } } var tag = new XmpTag (xmp); var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, true) as XmpTag; xmp_tag.ReplaceFrom (tag); } public static void SaveXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource) { var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, false) as XmpTag; if (xmp_tag == null) return; var xmp = xmp_tag.Render (); using (var stream = resource.WriteStream) { using (var writer = new StreamWriter (stream)) { writer.Write (xmp); } resource.CloseStream (stream); } } } } ``` Truncate stream when writing sidecar XMP files.
```c# using System; using System.IO; using GLib; using Hyena; using TagLib.Image; using TagLib.Xmp; namespace FSpot.Utils { public static class SidecarXmpExtensions { /// <summary> /// Parses the XMP file identified by resource and replaces the XMP /// tag of file by the parsed data. /// </summary> public static void ParseXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource) { string xmp; using (var stream = resource.ReadStream) { using (var reader = new StreamReader (stream)) { xmp = reader.ReadToEnd (); } } var tag = new XmpTag (xmp); var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, true) as XmpTag; xmp_tag.ReplaceFrom (tag); } public static void SaveXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource) { var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, false) as XmpTag; if (xmp_tag == null) return; var xmp = xmp_tag.Render (); using (var stream = resource.WriteStream) { stream.SetLength (0); using (var writer = new StreamWriter (stream)) { writer.Write (xmp); } resource.CloseStream (stream); } } } } ```
17401f9a-0f44-4e7f-93c0-f4ecf1948a2d
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Screens; using osu.Game.Screens.Multi; using osu.Game.Screens.Multi.Lounge; using osu.Game.Screens.Multi.Lounge.Components; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseMultiScreen : ScreenTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Multiplayer), typeof(LoungeSubScreen), typeof(FilterControl) }; public TestCaseMultiScreen() { Multiplayer multi = new Multiplayer(); AddStep(@"show", () => LoadScreen(multi)); AddUntilStep(() => multi.IsCurrentScreen(), "wait until current"); AddStep(@"exit", multi.Exit); } } } ``` Remove exit step (needs login to show properly)
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Screens; using osu.Game.Screens.Multi; using osu.Game.Screens.Multi.Lounge; using osu.Game.Screens.Multi.Lounge.Components; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseMultiScreen : ScreenTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Multiplayer), typeof(LoungeSubScreen), typeof(FilterControl) }; public TestCaseMultiScreen() { Multiplayer multi = new Multiplayer(); AddStep(@"show", () => LoadScreen(multi)); } } } ```
3fa20f93-21a2-4bc8-b8d0-b48774aeecdc
{ "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 System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace DocumentFormat.OpenXml.Tests { public class TestContext { public TestContext(string currentTest) { this.TestName = currentTest; this.FullyQualifiedTestClassName = currentTest; } public string TestName { get; set; } public string FullyQualifiedTestClassName { get; set; } [MethodImpl(MethodImplOptions.NoInlining)] public static string GetCurrentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(1); return sf.GetMethod().Name; } } } ``` Replace StackTrace with CallerMemberName attribute
```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 System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace DocumentFormat.OpenXml.Tests { public class TestContext { public TestContext(string currentTest) { this.TestName = currentTest; this.FullyQualifiedTestClassName = currentTest; } public string TestName { get; set; } public string FullyQualifiedTestClassName { get; set; } public static string GetCurrentMethod([CallerMemberName]string name = null) => name; } } ```
d592d503-a7a3-46de-b607-0614ae00715c
{ "language": "C#" }
```c# using System; using System.Linq; using Android.OS; using Android.Util; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; using ListFragment = Android.Support.V4.App.ListFragment; namespace Toggl.Joey.UI.Fragments { public class RecentTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); var headerView = new View (Activity); int headerWidth = (int) TypedValue.ApplyDimension (ComplexUnitType.Dip, 6, Resources.DisplayMetrics); headerView.SetMinimumHeight (headerWidth); ListView.AddHeaderView (headerView); ListAdapter = new RecentTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { RecentTimeEntriesAdapter adapter = null; if (l.Adapter is HeaderViewListAdapter) { var headerAdapter = (HeaderViewListAdapter)l.Adapter; adapter = headerAdapter.WrappedAdapter as RecentTimeEntriesAdapter; // Adjust the position by taking into account the fact that we've got headers position -= headerAdapter.HeadersCount; } else if (l.Adapter is RecentTimeEntriesAdapter) { adapter = (RecentTimeEntriesAdapter)l.Adapter; } if (adapter == null) return; var model = adapter.GetModel (position); if (model == null) return; model.Continue (); } } } ``` Fix potential crash when clicking on header/footer in recent list.
```c# using System; using System.Linq; using Android.OS; using Android.Util; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; using ListFragment = Android.Support.V4.App.ListFragment; namespace Toggl.Joey.UI.Fragments { public class RecentTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); var headerView = new View (Activity); int headerWidth = (int) TypedValue.ApplyDimension (ComplexUnitType.Dip, 6, Resources.DisplayMetrics); headerView.SetMinimumHeight (headerWidth); ListView.AddHeaderView (headerView); ListAdapter = new RecentTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { RecentTimeEntriesAdapter adapter = null; if (l.Adapter is HeaderViewListAdapter) { var headerAdapter = (HeaderViewListAdapter)l.Adapter; adapter = headerAdapter.WrappedAdapter as RecentTimeEntriesAdapter; // Adjust the position by taking into account the fact that we've got headers position -= headerAdapter.HeadersCount; } else if (l.Adapter is RecentTimeEntriesAdapter) { adapter = (RecentTimeEntriesAdapter)l.Adapter; } if (adapter == null || position < 0 || position >= adapter.Count) return; var model = adapter.GetModel (position); if (model == null) return; model.Continue (); } } } ```
555ea92c-4fe1-411d-a9dd-2fc05250b958
{ "language": "C#" }
```c# using System.IO; using Microsoft.AspNetCore.Hosting; using Orchard.Hosting; using Orchard.Web; namespace Orchard.Console { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseWebRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); using (host) { host.Run(); var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args); orchardHost.Run(); } } } }``` Stop double call of Directory.GetCurrentDirectory on startup, as 20% slower on linux
```c# using System.IO; using Microsoft.AspNetCore.Hosting; using Orchard.Hosting; using Orchard.Web; namespace Orchard.Console { public class Program { public static void Main(string[] args) { var currentDirectory = Directory.GetCurrentDirectory(); var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(currentDirectory) .UseWebRoot(currentDirectory) .UseStartup<Startup>() .Build(); using (host) { host.Run(); var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args); orchardHost.Run(); } } } }```
da0326ed-8db9-47f0-ae56-9cff17980dce
{ "language": "C#" }
```c# namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddIntegerIntegerOperation : IBinaryOperation<int, int, int> { public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2) { Tensor<int> result = new Tensor<int>(); result.SetValue(tensor1.GetValue() + tensor2.GetValue()); return result; return result; } } } ``` Refactor Add Integers Operation to use GetValues and CloneWithValues
```c# namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddIntegerIntegerOperation : IBinaryOperation<int, int, int> { public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2) { int[] values1 = tensor1.GetValues(); int l = values1.Length; int[] values2 = tensor2.GetValues(); int[] newvalues = new int[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] + values2[k]; return tensor1.CloneWithNewValues(newvalues); } } } ```
9d1cc2a7-672d-43a9-9750-c5a4f5c1bcef
{ "language": "C#" }
```c# namespace SharpMath.Geometry { public static class VectorExtensions { public static T Negate<T>(this Vector vector) where T : Vector, new() { var resultVector = new T(); for (uint i = 0; i < vector.Dimension; ++i) resultVector[i] = -vector[i]; return resultVector; } /// <summary> /// Calculates the normalized <see cref="Vector"/> of this <see cref="Vector"/>. /// </summary> /// <returns>The normalized <see cref="Vector"/>.</returns> public static T Normalize<T>(this Vector vector) where T : Vector, new() { var resultVector = new T(); for (uint i = 0; i < vector.Dimension; ++i) resultVector[i] /= vector.Magnitude; return resultVector; } } }``` Fix normalizing a vector results in a zero vector
```c# using SharpMath.Geometry.Exceptions; namespace SharpMath.Geometry { public static class VectorExtensions { public static T Negate<T>(this Vector vector) where T : Vector, new() { var resultVector = new T(); if (vector.Dimension != resultVector.Dimension) throw new DimensionException("The dimensions of the vectors do not equal each other."); for (uint i = 0; i < vector.Dimension; ++i) resultVector[i] = -vector[i]; return resultVector; } /// <summary> /// Calculates the normalized <see cref="Vector"/> of this <see cref="Vector"/>. /// </summary> /// <returns>The normalized <see cref="Vector"/>.</returns> public static T Normalize<T>(this Vector vector) where T : Vector, new() { var resultVector = new T(); if (vector.Dimension != resultVector.Dimension) throw new DimensionException("The dimensions of the vectors do not equal each other."); for (uint i = 0; i < vector.Dimension; ++i) resultVector[i] = vector[i] / vector.Magnitude; return resultVector; } } }```
55372b33-5813-474b-abc0-064590a549f7
{ "language": "C#" }
```c# // Copyright 2009 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using NUnit.Framework; using NDesk.DBus; namespace NDesk.DBus.Tests { [TestFixture] public class SignatureTest { [Test] public void Parse () { string sigText = "as"; Signature sig = new Signature (sigText); Assert.IsTrue (sig.IsArray); Assert.IsFalse (sig.IsDict); Assert.IsFalse (sig.IsPrimitive); } } } ``` Add test for Signature equality
```c# // Copyright 2009 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using NUnit.Framework; using NDesk.DBus; namespace NDesk.DBus.Tests { [TestFixture] public class SignatureTest { [Test] public void Parse () { string sigText = "as"; Signature sig = new Signature (sigText); Assert.IsTrue (sig.IsArray); Assert.IsFalse (sig.IsDict); Assert.IsFalse (sig.IsPrimitive); } [Test] public void Equality () { string sigText = "as"; Signature a = new Signature (sigText); Signature b = new Signature (sigText); Assert.IsTrue (a == b); } } } ```
88858e5e-fd73-415b-bb44-98810eb6da07
{ "language": "C#" }
```c# <h2>What is dotnet signals?</h2> .NET Signals is a community driven link aggregator for the sharing of knowledge in the .NET community. Our focus is to give the .NET community a place to post ideas and knowledge as voted by the community while avoiding the clutter found in traditional sources. <h2>Posts</h2> <ul> <li>Try to keep the title of the post the same as the article except to add information on vague titles,</li> <li>Posts should be related to the .Net ecosystem or to information regarding technologies that the .Net community would find helpful or interesting,</li> <li>Meta posts and bugs should be created on the github issues page as either discussion or bug,</li> <li>Posts seeking help (homework, how do I do X, etc) are not suited for .NET Signals. Consider asking your questions on the .NET subreddit or stackoverflow.</li> </ul> <h2>Comments</h2> <ul> <li>Do not spam,</li> <li>Avoid Me toos, thanks, "awesome post" comments,</li> <li>Be professional, be polite.</li> </ul>``` Add layout to guidelines page.
```c# @{ ViewData["Title"] = "Guidelines"; Layout = "~/Views/Shared/_Layout.cshtml"; } <section> <h2>What is dotnet signals?</h2> .NET Signals is a community driven link aggregator for the sharing of knowledge in the .NET community. Our focus is to give the .NET community a place to post ideas and knowledge as voted by the community while avoiding the clutter found in traditional sources. <h2>Posts</h2> <ul> <li>Try to keep the title of the post the same as the article except to add information on vague titles,</li> <li>Posts should be related to the .Net ecosystem or to information regarding technologies that the .Net community would find helpful or interesting,</li> <li>Meta posts and bugs should be created on the github issues page as either discussion or bug,</li> <li>Posts seeking help (homework, how do I do X, etc) are not suited for .NET Signals. Consider asking your questions on the .NET subreddit or stackoverflow.</li> </ul> <h2>Comments</h2> <ul> <li>Do not spam,</li> <li>Avoid Me toos, thanks, "awesome post" comments,</li> <li>Be professional, be polite.</li> </ul> </section> ```
ac2e7ea8-9287-48a9-b311-1f418029bb73
{ "language": "C#" }
```c# // Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] ``` Add a couple of friend assemblies
```c# // Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")] ```
ac6620b8-f369-4d59-9682-6bc656c06a0e
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using osu.Game.Online.Chat; namespace osu.Game.Online.API.Requests { public class GetUpdatesResponse { public List<Channel> Presence; public List<Message> Messages; } } ``` Add explicit usage via attribute
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Online.Chat; namespace osu.Game.Online.API.Requests { public class GetUpdatesResponse { [JsonProperty] public List<Channel> Presence; [JsonProperty] public List<Message> Messages; } } ```
ea3e4987-2f5e-4a62-acb8-8634e72a75d0
{ "language": "C#" }
```c# using System; using ColossalFramework; using ColossalFramework.Plugins; using ICities; using ModTools.Utils; using UnityEngine; namespace ModTools { public sealed class ModToolsMod : IUserMod { public const string ModToolsName = "ModTools"; public static GameObject MainWindowObject; private static GameObject mainObject; public static string Version { get; } = GitVersion.GetAssemblyVersion(typeof(ModToolsMod).Assembly); public string Name => ModToolsName; public string Description => "Debugging toolkit for modders, version " + Version; public void OnEnabled() { try { if (MainWindowObject != null) { return; } CODebugBase<LogChannel>.verbose = true; CODebugBase<LogChannel>.EnableChannels(LogChannel.All); mainObject = new GameObject(ModToolsName); UnityEngine.Object.DontDestroyOnLoad(mainObject); MainWindowObject = new GameObject(ModToolsName + nameof(MainWindow)); UnityEngine.Object.DontDestroyOnLoad(MainWindowObject); var modTools = MainWindowObject.AddComponent<MainWindow>(); modTools.Initialize(); } catch (Exception e) { DebugOutputPanel.AddMessage(PluginManager.MessageType.Error, e.Message); } } public void OnDisabled() { if (MainWindowObject != null) { CODebugBase<LogChannel>.verbose = false; UnityEngine.Object.Destroy(MainWindowObject); MainWindowObject = null; } if (mainObject != null) { CODebugBase<LogChannel>.verbose = false; UnityEngine.Object.Destroy(mainObject); mainObject = null; } } } }``` Make mainObject an instance field
```c# using System; using ColossalFramework; using ColossalFramework.Plugins; using ICities; using ModTools.Utils; using UnityEngine; namespace ModTools { public sealed class ModToolsMod : IUserMod { public const string ModToolsName = "ModTools"; public static GameObject MainWindowObject; private GameObject mainObject; public static string Version { get; } = GitVersion.GetAssemblyVersion(typeof(ModToolsMod).Assembly); public string Name => ModToolsName; public string Description => "Debugging toolkit for modders, version " + Version; public void OnEnabled() { try { if (MainWindowObject != null) { return; } CODebugBase<LogChannel>.verbose = true; CODebugBase<LogChannel>.EnableChannels(LogChannel.All); mainObject = new GameObject(ModToolsName); UnityEngine.Object.DontDestroyOnLoad(mainObject); MainWindowObject = new GameObject(ModToolsName + nameof(MainWindow)); UnityEngine.Object.DontDestroyOnLoad(MainWindowObject); var modTools = MainWindowObject.AddComponent<MainWindow>(); modTools.Initialize(); } catch (Exception e) { DebugOutputPanel.AddMessage(PluginManager.MessageType.Error, e.Message); } } public void OnDisabled() { if (MainWindowObject != null) { CODebugBase<LogChannel>.verbose = false; UnityEngine.Object.Destroy(MainWindowObject); MainWindowObject = null; } if (mainObject != null) { CODebugBase<LogChannel>.verbose = false; UnityEngine.Object.Destroy(mainObject); mainObject = null; } } } }```
2c37e677-4a7d-432a-8707-dc108ec3691c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NTST.ScriptLinkService.Objects; namespace ScriptLinkCore { public partial class ScriptLink { /// <summary> /// Used set required fields /// </summary> /// <param name="optionObject"></param> /// <param name="fieldNumber"></param> /// <returns></returns> public static OptionObject SetRequiredField(OptionObject optionObject, string fieldNumber) { OptionObject returnOptionObject = optionObject; Boolean updated = false; foreach (var form in returnOptionObject.Forms) { foreach (var currentField in form.CurrentRow.Fields) { if (currentField.FieldNumber == fieldNumber) { currentField.Required = "1"; updated = true; } } } if (updated == true) { foreach (var form in returnOptionObject.Forms) { form.CurrentRow.RowAction = "EDIT"; } return returnOptionObject; } else { return optionObject; } } } } ``` Change to use ScriptLinkCore.Objects namespace
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ScriptLinkCore.Objects; namespace ScriptLinkCore { public partial class ScriptLink { /// <summary> /// Used set required fields /// </summary> /// <param name="optionObject"></param> /// <param name="fieldNumber"></param> /// <returns></returns> public static OptionObject SetRequiredField(OptionObject optionObject, string fieldNumber) { OptionObject returnOptionObject = optionObject; Boolean updated = false; foreach (var form in returnOptionObject.Forms) { foreach (var currentField in form.CurrentRow.Fields) { if (currentField.FieldNumber == fieldNumber) { currentField.Required = "1"; updated = true; } } } if (updated == true) { foreach (var form in returnOptionObject.Forms) { form.CurrentRow.RowAction = "EDIT"; } return returnOptionObject; } else { return optionObject; } } } } ```
08f86d20-b6c3-4972-8bdc-ae76c41e42f6
{ "language": "C#" }
```c# using System; namespace InfluxDB.Net.Collector.Console { static class Program { private static InfluxDb _client; static void Main(string[] args) { if (args.Length != 3) { //url: http://128.199.43.107:8086 //username: root //Password: ????? throw new InvalidOperationException("Three parameters needs to be provided to this application. url, username and password for the InfluxDB database."); } var url = args[0]; var username = args[1]; var password = args[2]; _client = new InfluxDb(url, username, password); var pong = _client.PingAsync().Result; System.Console.WriteLine("Ping: {0} ({1} ms)", pong.Status, pong.ResponseTime); var version = _client.VersionAsync().Result; System.Console.WriteLine("Version: {0}", version); System.Console.WriteLine("Press any key to exit..."); System.Console.ReadKey(); } } }``` Send single sample of processor performance counter to the InfluxDB.Net.
```c# using System; using System.Diagnostics; using InfluxDB.Net.Models; namespace InfluxDB.Net.Collector.Console { static class Program { private static InfluxDb _client; static void Main(string[] args) { if (args.Length != 3) { //url: http://128.199.43.107:8086 //username: root //Password: ????? throw new InvalidOperationException("Three parameters needs to be provided to this application. url, username and password for the InfluxDB database."); } var url = args[0]; var username = args[1]; var password = args[2]; _client = new InfluxDb(url, username, password); var pong = _client.PingAsync().Result; System.Console.WriteLine("Ping: {0} ({1} ms)", pong.Status, pong.ResponseTime); var version = _client.VersionAsync().Result; System.Console.WriteLine("Version: {0}", version); var processorCounter = GetPerformanceCounter(); System.Threading.Thread.Sleep(100); var result = RegisterCounterValue(processorCounter); System.Console.WriteLine(result.StatusCode); System.Console.WriteLine("Press enter to exit..."); System.Console.ReadKey(); } private static InfluxDbApiResponse RegisterCounterValue(PerformanceCounter processorCounter) { var data = processorCounter.NextValue(); System.Console.WriteLine("Processor value: {0}%", data); var serie = new Serie.Builder("Processor") .Columns("Total") .Values(data) .Build(); var result = _client.WriteAsync("QTest", TimeUnit.Milliseconds, serie); return result.Result; } private static PerformanceCounter GetPerformanceCounter() { var processorCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); processorCounter.NextValue(); return processorCounter; } } }```
c3e39239-8bb4-4ca9-8ffd-f2eda744d444
{ "language": "C#" }
```c# // Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Tooling; namespace Nuke.Common.Tools.Unity { public partial class UnityBaseSettings { public override Action<OutputType, string> ProcessCustomLogger => UnityTasks.UnityLogger; public string GetProcessToolPath() { return UnityTasks.GetToolPath(HubVersion); } public string GetLogFile() { // TODO SK return LogFile ?? NukeBuild.RootDirectory / "unity.log"; } } } ``` Fix quoting for Unity log file
```c# // Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Tooling; using Nuke.Common.Utilities; namespace Nuke.Common.Tools.Unity { public partial class UnityBaseSettings { public override Action<OutputType, string> ProcessCustomLogger => UnityTasks.UnityLogger; public string GetProcessToolPath() { return UnityTasks.GetToolPath(HubVersion); } public string GetLogFile() { return (LogFile ?? NukeBuild.RootDirectory / "unity.log").DoubleQuoteIfNeeded(); } } } ```
0962615c-c952-4440-a7ac-8781048aed27
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class Nanobot : MonoBehaviour, TimestepManager.TimestepListener { BulletGridGenerator currentLevel; public NanobotSchematic schematic; public int price; public string id; // Use this for initialization void Start() { currentLevel = FindObjectOfType<BulletGridGenerator>(); GameObject.FindObjectOfType<TimestepManager>().addListener(this); schematic = GameObject.Instantiate(schematic); } public void notifyTimestep() { currentLevel.getCellAt(gameObject.GetComponent<GridPositionComponent>().position).Cell.GetComponent<Cell>().Eat(1, false); for (int x = 0; x < schematic.getTransformation().Length; x++) { if (schematic.getTransformation()[x] != null) { for (int y = 0; y < schematic.getTransformation()[x].Length; y++) { if (schematic.getTransformation()[x][y] != null) { currentLevel.moveBotAnimated(gameObject.GetComponent<GridPositionComponent>().position, schematic.getTransformation()[x][y], new GridPosition(x - 1, y - 1), 5, false); } } } } } } ``` Handle exiting if bot is destroyed by consuming resources.
```c# using UnityEngine; using System.Collections; public class Nanobot : MonoBehaviour, TimestepManager.TimestepListener { BulletGridGenerator currentLevel; public NanobotSchematic schematic; public int price; public string id; // Use this for initialization void Start() { currentLevel = FindObjectOfType<BulletGridGenerator>(); GameObject.FindObjectOfType<TimestepManager>().addListener(this); schematic = GameObject.Instantiate(schematic); } public void notifyTimestep() { GridPosition position = gameObject.GetComponent<GridPositionComponent>().position; BulletGridGenerator.GameCell cell = currentLevel.getCellAt(position); cell.Cell.GetComponent<Cell>().Eat(1, false); if (cell.Nanobot == null) { // TODO: Trigger animation for nanobot death. return; } for (int x = 0; x < schematic.getTransformation().Length; x++) { if (schematic.getTransformation()[x] != null) { for (int y = 0; y < schematic.getTransformation()[x].Length; y++) { if (schematic.getTransformation()[x][y] != null) { currentLevel.moveBotAnimated(position, schematic.getTransformation()[x][y], new GridPosition(x - 1, y - 1), 5, false); } } } } } } ```
470b09a4-017b-4d08-bad5-74bd4b7789f5
{ "language": "C#" }
```c# namespace SimpleLogger.Logging.Formatters { internal class DefaultLoggerFormatter : ILoggerFormatter { public string ApplyFormat(LogMessage logMessage) { return string.Format("{0:dd.MM.yyyy HH:mm}: {1} ln: {2} [{3} -> {4}()]: {5}", logMessage.DateTime, logMessage.Level, logMessage.LineNumber, logMessage.CallingClass, logMessage.CallingMethod, logMessage.Text); } } }``` Change format on default logger formatter.
```c# namespace SimpleLogger.Logging.Formatters { internal class DefaultLoggerFormatter : ILoggerFormatter { public string ApplyFormat(LogMessage logMessage) { return string.Format("{0:dd.MM.yyyy HH:mm}: {1} [line: {2} {3} -> {4}()]: {5}", logMessage.DateTime, logMessage.Level, logMessage.LineNumber, logMessage.CallingClass, logMessage.CallingMethod, logMessage.Text); } } }```
b9ccbd19-ff01-4590-9d23-71a1da18495b
{ "language": "C#" }
```c# using System.IO; using System.Reflection; using NServiceBus.Persistence.Sql.ScriptBuilder; static class ResourceReader { static Assembly assembly = typeof(ResourceReader).GetTypeInfo().Assembly; public static string ReadResource(BuildSqlDialect sqlDialect, string prefix) { var text = $"NServiceBus.Persistence.Sql.{prefix}_{sqlDialect}.sql"; using (var stream = assembly.GetManifestResourceStream(text)) using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } } }``` Revise expected resource name after fixing default namespace
```c# using System.IO; using System.Reflection; using NServiceBus.Persistence.Sql.ScriptBuilder; static class ResourceReader { static Assembly assembly = typeof(ResourceReader).GetTypeInfo().Assembly; public static string ReadResource(BuildSqlDialect sqlDialect, string prefix) { var text = $"NServiceBus.Persistence.Sql.ScriptBuilder.{prefix}_{sqlDialect}.sql"; using (var stream = assembly.GetManifestResourceStream(text)) using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } } }```
21b207d0-c32b-4754-bade-e8d88b363a73
{ "language": "C#" }
```c# <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"]–FAV Rocks</title> <link rel="shortcut icon" href="~/favicon.ico" /> <environment names="Development"> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment> @RenderSection("styles", required: false) </head> <body> <header> <div id="title-container"> <a id="title" asp-controller="Home" asp-action="Index">FAV \m/</a> <a id="about" asp-controller="About">About</a> </div> <h3 id="tagline">The most accessible and efficient favicon editor</h3> </header> <hr /> @RenderBody() <hr /> <footer> <p>&copy; @DateTimeOffset.Now.Year, <a href="https://www.billboga.com/">Bill Boga</a>. </footer> @RenderSection("scripts", required: false) </body> </html> ``` Add language declaration to layout
```c# <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"]–FAV Rocks</title> <link rel="shortcut icon" href="~/favicon.ico" /> <environment names="Development"> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment> @RenderSection("styles", required: false) </head> <body> <header> <div id="title-container"> <a id="title" asp-controller="Home" asp-action="Index">FAV \m/</a> <a id="about" asp-controller="About">About</a> </div> <h3 id="tagline">The most accessible and efficient favicon editor</h3> </header> <hr /> @RenderBody() <hr /> <footer> <p>&copy; @DateTimeOffset.Now.Year, <a href="https://www.billboga.com/">Bill Boga</a>. </footer> @RenderSection("scripts", required: false) </body> </html> ```
592eb5ca-69aa-4e6f-9346-91a48acba5f2
{ "language": "C#" }
```c# using System.IO; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; namespace Neo4jManager.Host { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .ConfigureServices(services => services.AddAutofac()) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } } ``` Set port 7400 and use default WebHost builder
```c# using System.IO; using System.Net; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace Neo4jManager.Host { public class Program { public static void Main(string[] args) { var host = WebHost.CreateDefaultBuilder(args) .UseKestrel(options => options.Listen(IPAddress.Loopback, 7400)) .ConfigureServices(services => services.AddAutofac()) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } } ```
70d7e6a3-c590-4516-a411-cd55b00c3215
{ "language": "C#" }
```c# /* * Copyright 2012 Xamarin, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Dynamic; using Newtonsoft.Json.Linq; namespace Xamarin.Payments.Stripe { public class StripeEvent : StripeObject { [JsonProperty (PropertyName = "livemode")] bool LiveMode { get; set; } [JsonProperty (PropertyName = "created")] [JsonConverter (typeof (UnixDateTimeConverter))] public DateTime? Created { get; set; } [JsonProperty (PropertyName = "type")] public string type { get; set; } [JsonProperty (PropertyName= "data")] public EventData Data { get; set; } public class EventData { [JsonProperty (PropertyName = "object")] [JsonConverter (typeof (StripeObjectConverter))] public StripeObject Object { get; set; } } } } ``` Fix some details of the event object
```c# /* * Copyright 2012 Xamarin, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; namespace Xamarin.Payments.Stripe { public class StripeEvent : StripeObject { [JsonProperty (PropertyName = "livemode")] public bool LiveMode { get; set; } [JsonProperty (PropertyName = "created")] [JsonConverter (typeof (UnixDateTimeConverter))] public DateTime? Created { get; set; } [JsonProperty (PropertyName = "type")] public string Type { get; set; } [JsonProperty (PropertyName= "data")] public EventData Data { get; set; } public class EventData { [JsonProperty (PropertyName = "object")] [JsonConverter (typeof (StripeObjectConverter))] public StripeObject Object { get; set; } [JsonProperty (PropertyName = "previous_attributes")] public JObject PreviousAttributes { get; set; } } } } ```
e09b7e40-e0f1-4eb1-a6d7-12194c457d3e
{ "language": "C#" }
```c# using System; using OpenTK.Graphics.OpenGL; using System.Diagnostics; using ChamberLib.Content; namespace ChamberLib.OpenTK { public class ShaderStage : IShaderStage { public ShaderStage(ShaderContent content) : this(content.Source, content.Type, content.Name) { } public ShaderStage(string source, ShaderType shaderType, string name) { Source = source; ShaderType = shaderType; Name = name; } public string Name { get; protected set; } public int ShaderID { get; protected set; } public string Source { get; protected set; } public ShaderType ShaderType { get; protected set; } public void MakeReady() { if (ShaderID != 0) return; GLHelper.CheckError(); ShaderID = GL.CreateShader(ShaderType.ToOpenTK()); GLHelper.CheckError(); GL.ShaderSource(ShaderID, Source); GLHelper.CheckError(); GL.CompileShader(ShaderID); GLHelper.CheckError(); int result; GL.GetShader(ShaderID, ShaderParameter.CompileStatus, out result); Debug.WriteLine("{1} compile status: {0}", result, ShaderType); GLHelper.CheckError(); Debug.WriteLine("{0} info:", ShaderType); Debug.WriteLine(GL.GetShaderInfoLog(ShaderID)); GLHelper.CheckError(); } } } ``` Use a flag to indicate if the shader stage has been successfully compiled.
```c# using System; using OpenTK.Graphics.OpenGL; using System.Diagnostics; using ChamberLib.Content; using _OpenTK = global::OpenTK; namespace ChamberLib.OpenTK { public class ShaderStage : IShaderStage { public ShaderStage(ShaderContent content) : this(content.Source, content.Type, content.Name) { } public ShaderStage(string source, ShaderType shaderType, string name) { Source = source; ShaderType = shaderType; Name = name; } public string Name { get; protected set; } public int ShaderID { get; protected set; } public string Source { get; protected set; } public ShaderType ShaderType { get; protected set; } public bool IsCompiled { get; protected set; } public void MakeReady() { GLHelper.CheckError(); if (ShaderID == 0) { ShaderID = GL.CreateShader(ShaderType.ToOpenTK()); GLHelper.CheckError(); IsCompiled = false; } if (!IsCompiled) { GL.ShaderSource(ShaderID, Source); GLHelper.CheckError(); GL.CompileShader(ShaderID); GLHelper.CheckError(); int result; GL.GetShader(ShaderID, ShaderParameter.CompileStatus, out result); Debug.WriteLine("{1} compile status: {0}", result, ShaderType); GLHelper.CheckError(); Debug.WriteLine("{0} info:", ShaderType); Debug.WriteLine(GL.GetShaderInfoLog(ShaderID)); GLHelper.CheckError(); IsCompiled = (result == 1); } } } } ```
8e9f50dd-f8c2-41fa-ac66-2883afae33f9
{ "language": "C#" }
```c# namespace Espera.Network { public enum ResponseStatus { Success, PlaylistEntryNotFound, Unauthorized, MalformedRequest, NotFound, NotSupported, Rejected, Fatal } }``` Add a wrong password status
```c# namespace Espera.Network { public enum ResponseStatus { Success, PlaylistEntryNotFound, Unauthorized, MalformedRequest, NotFound, NotSupported, Rejected, Fatal, WrongPassword } }```
426ff2f5-e03e-4322-ad24-4703ea15b5d8
{ "language": "C#" }
```c# using System.Web; using System.Web.Optimization; namespace Quiz.Web { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/jquery.pietimer").Include( "~/Scripts/jquery.pietimer.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/style").Include( "~/Scripts/style.css")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } } ``` Fix Otimização desabilitada para teste
```c# using System.Web; using System.Web.Optimization; namespace Quiz.Web { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/jquery.pietimer").Include( "~/Scripts/jquery.pietimer.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/style").Include( "~/Scripts/style.css")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); BundleTable.EnableOptimizations = false; } } } ```
06bdc5e4-046b-4885-9ef8-df997154d220
{ "language": "C#" }
```c# using System.Linq; namespace HundredDoors { public static class HundredDoors { /// <summary> /// Solves the 100 Doors problem /// </summary> /// <returns>An array with 101 values, each representing a door (except 0). True = open</returns> public static bool[] Solve() { // Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it bool[] doors = Enumerable.Repeat(false, 101).ToArray(); // We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door for (int pass = 1; pass <= 100; pass++) for (int i = pass; i < doors.Length; i += pass) doors[i] = !doors[i]; return doors; //final door count } } } ``` Revert "Added "final door count" comment at return value."
```c# using System.Linq; namespace HundredDoors { public static class HundredDoors { /// <summary> /// Solves the 100 Doors problem /// </summary> /// <returns>An array with 101 values, each representing a door (except 0). True = open</returns> public static bool[] Solve() { // Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it bool[] doors = Enumerable.Repeat(false, 101).ToArray(); // We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door for (int pass = 1; pass <= 100; pass++) for (int i = pass; i < doors.Length; i += pass) doors[i] = !doors[i]; return doors; } } } ```
99a61aaf-3876-4979-8f14-d6e6aa53fd7e
{ "language": "C#" }
```c# namespace Espera.Network { public enum NetworkSongSource { Local = 0, Youtube = 1, Remote = 2 } }``` Rename that to avoid confusion
```c# namespace Espera.Network { public enum NetworkSongSource { Local = 0, Youtube = 1, Mobile = 2 } }```
362bc351-0508-4e99-a63a-bb49da2d487d
{ "language": "C#" }
```c# @model IEnumerable<GiveCRM.Models.Member> @foreach (var member in Model) { <a href="javascript:AddDonation(@member.Id);">@member.FirstName @member.LastName @member.PostalCode</a><br /> }``` Remove page styling from Ajax search results.
```c# @model IEnumerable<GiveCRM.Models.Member> @{ Layout = null; } @foreach (var member in Model) { <p style="margin:0; padding:0;"><a href="javascript:AddDonation(@member.Id);">@member.FirstName @member.LastName @member.PostalCode</a></p> }```
6be45221-2157-4a2f-a8c2-8f7914ab9c6d
{ "language": "C#" }
```c# using Microsoft.AspNet.Abstractions; namespace KWebStartup { public class Startup { public void Configuration(IBuilder app) { app.Run(async context => { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello world"); }); } } }``` Add missing namespace to the sample.
```c# using Microsoft.AspNet; using Microsoft.AspNet.Abstractions; namespace KWebStartup { public class Startup { public void Configuration(IBuilder app) { app.Run(async context => { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello world"); }); } } }```
fb50b09f-63ef-4cba-afd7-fa43c583650f
{ "language": "C#" }
```c# using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Http.Dispatcher; using Pablo.Gallery.Logic; using Pablo.Gallery.Logic.Filters; using System.Web.Http.Controllers; using Pablo.Gallery.Logic.Selectors; namespace Pablo.Gallery { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new LoggingApiExceptionFilter()); config.Routes.MapHttpRoute( name: "api", routeTemplate: "api/{version}/{controller}/{id}/{*path}", defaults: new { version = "v0", id = RouteParameter.Optional, path = RouteParameter.Optional } ); config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config, 1)); config.Formatters.JsonFormatter.AddQueryStringMapping("type", "json", "application/json"); config.Formatters.XmlFormatter.AddQueryStringMapping("type", "xml", "application/xml"); //config.MessageHandlers.Add(new CorsHandler()); config.Services.Replace(typeof(IHttpActionSelector), new CorsPreflightActionSelector()); } } } ``` Fix issue with ms asp.net getting httproute paths with a wildcard
```c# using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Http.Dispatcher; using Pablo.Gallery.Logic; using Pablo.Gallery.Logic.Filters; using System.Web.Http.Controllers; using Pablo.Gallery.Logic.Selectors; namespace Pablo.Gallery { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new LoggingApiExceptionFilter()); config.Routes.MapHttpRoute( name: "api", routeTemplate: "api/{version}/{controller}/{id}", defaults: new { version = "v0", id = RouteParameter.Optional } ); // need this separate as Url.RouteUrl does not work with a wildcard in the route // this is used to allow files in subfolders of a pack to be retrieved. config.Routes.MapHttpRoute( name: "apipath", routeTemplate: "api/{version}/{controller}/{id}/{*path}", defaults: new { version = "v0", id = RouteParameter.Optional, path = RouteParameter.Optional } ); config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config, 1)); config.Formatters.JsonFormatter.AddQueryStringMapping("type", "json", "application/json"); config.Formatters.XmlFormatter.AddQueryStringMapping("type", "xml", "application/xml"); //config.MessageHandlers.Add(new CorsHandler()); config.Services.Replace(typeof(IHttpActionSelector), new CorsPreflightActionSelector()); } } } ```
5f795f0f-89bb-41db-ba77-9e81a622310a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using TwitchLib; using TwitchLib.TwitchClientClasses; using System.Net; namespace JefBot.Commands { internal class CoinPluginCommand : IPluginCommand { public string PluginName => "Coin"; public string Command => "coin"; public IEnumerable<string> Aliases => new[] { "c", "flip" }; public bool Loaded { get; set; } = true; public bool OffWhileLive { get; set; } = true; Random rng = new Random(); public void Execute(ChatCommand command, TwitchClient client) { if (rng.Next(1000) > 1) { var result = rng.Next(0, 1) == 1 ? "heads" : "tails"; client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it was {result}"); } else { client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it landed on it's side..."); } } } } ``` Allow coin flip to be heads.
```c# using System; using System.Collections.Generic; using System.IO; using TwitchLib; using TwitchLib.TwitchClientClasses; using System.Net; namespace JefBot.Commands { internal class CoinPluginCommand : IPluginCommand { public string PluginName => "Coin"; public string Command => "coin"; public IEnumerable<string> Aliases => new[] { "c", "flip" }; public bool Loaded { get; set; } = true; public bool OffWhileLive { get; set; } = true; Random rng = new Random(); public void Execute(ChatCommand command, TwitchClient client) { if (rng.Next(1000) > 1) { var result = rng.Next(0, 2) == 1 ? "heads" : "tails"; client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it was {result}"); } else { client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it landed on it's side..."); } } } } ```
c2550dc0-14ea-4bc9-b57b-7f700c0ee11a
{ "language": "C#" }
```c# //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Desktop; using osu.Framework.Desktop.Platform; using osu.Framework.Platform; using osu.Game.Modes; using osu.Game.Modes.Catch; using osu.Game.Modes.Mania; using osu.Game.Modes.Osu; using osu.Game.Modes.Taiko; namespace osu.Desktop.VisualTests { public static class Program { [STAThread] public static void Main(string[] args) { using (BasicGameHost host = Host.GetSuitableHost(@"osu-visual-tests")) { Ruleset.Register(new OsuRuleset()); Ruleset.Register(new TaikoRuleset()); Ruleset.Register(new ManiaRuleset()); Ruleset.Register(new CatchRuleset()); host.Add(new VisualTestGame()); host.Run(); } } } } ``` Allow visualtests to share config etc. with osu!.
```c# //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Desktop; using osu.Framework.Desktop.Platform; using osu.Framework.Platform; using osu.Game.Modes; using osu.Game.Modes.Catch; using osu.Game.Modes.Mania; using osu.Game.Modes.Osu; using osu.Game.Modes.Taiko; namespace osu.Desktop.VisualTests { public static class Program { [STAThread] public static void Main(string[] args) { using (BasicGameHost host = Host.GetSuitableHost(@"osu")) { Ruleset.Register(new OsuRuleset()); Ruleset.Register(new TaikoRuleset()); Ruleset.Register(new ManiaRuleset()); Ruleset.Register(new CatchRuleset()); host.Add(new VisualTestGame()); host.Run(); } } } } ```
a17d23b9-033e-40f5-8665-f27abbea36ef
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { /// <summary> /// Represents the different types available for a <see cref="Field"/>. /// </summary> public class SystemFieldTypes { /// <summary> /// Short text. /// </summary> public const string Symbol = "Symbol"; /// <summary> /// Long text. /// </summary> public const string Text = "Text"; /// <summary> /// An integer. /// </summary> public const string Integer = "Integer"; /// <summary> /// A floating point number. /// </summary> public const string Number = "Number"; /// <summary> /// A datetime. /// </summary> public const string Date = "Date"; /// <summary> /// A boolean value. /// </summary> public const string Boolean = "Boolean"; /// <summary> /// A location field. /// </summary> public const string Location = "Location"; /// <summary> /// A link to another asset or entry. /// </summary> public const string Link = "Link"; /// <summary> /// An array of objects. /// </summary> public const string Array = "Array"; /// <summary> /// An arbitrary json object. /// </summary> public const string Object = "Object"; } } ``` Add rich text to system field types
```c# using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { /// <summary> /// Represents the different types available for a <see cref="Field"/>. /// </summary> public class SystemFieldTypes { /// <summary> /// Short text. /// </summary> public const string Symbol = "Symbol"; /// <summary> /// Long text. /// </summary> public const string Text = "Text"; /// <summary> /// An integer. /// </summary> public const string Integer = "Integer"; /// <summary> /// A floating point number. /// </summary> public const string Number = "Number"; /// <summary> /// A datetime. /// </summary> public const string Date = "Date"; /// <summary> /// A boolean value. /// </summary> public const string Boolean = "Boolean"; /// <summary> /// A location field. /// </summary> public const string Location = "Location"; /// <summary> /// A link to another asset or entry. /// </summary> public const string Link = "Link"; /// <summary> /// An array of objects. /// </summary> public const string Array = "Array"; /// <summary> /// An arbitrary json object. /// </summary> public const string Object = "Object"; /// <summary> /// An rich text document. /// </summary> public const string RichText = "RichText"; } } ```
63a0e6bc-ae1a-4511-b9bf-cda5d43ead35
{ "language": "C#" }
```c# @model IEnumerable<APFT> <h2>Units @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> <th></th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td></td> </tr> } </tbody> </table>``` Add stub for APFT list
```c# @model IEnumerable<APFT> <h2>Units @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td>@Html.DisplayFor(_ => model.Date)</td> <td>@Html.DisplayFor(_ => model.PushUps)</td> <td>@Html.DisplayFor(_ => model.SitUps)</td> <td>@Html.DisplayFor(_ => model.Run)</td> <td>@Html.DisplayFor(_ => model.TotalScore)</td> <td>@Html.DisplayFor(_ => model.IsPassing)</td> </tr> } </tbody> </table>```
f53256d7-bb69-4083-8b69-ebc9d504baaa
{ "language": "C#" }
```c# using System; using System.Runtime.CompilerServices; namespace Mindscape.Raygun4Net { public static class APM { [ThreadStatic] private static bool _enabled = false; [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void Enable() { _enabled = true; } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void Disable() { _enabled = false; } public static bool IsEnabled { get { return _enabled; } } public static bool ProfilerAttached { get { #if NETSTANDARD1_6 || NETSTANDARD2_0 // Look for .NET CORE compatible Environment Variables return Environment.GetEnvironmentVariable("CORECLR_PROFILER") == "{e2338988-38cc-48cd-a6b6-b441c31f34f1}" && Environment.GetEnvironmentVariable("CORECLR_ENABLE_PROFILING") == "1"; #else // Look for .NET FRAMEWORK compatible Environment Variables return Environment.GetEnvironmentVariable("COR_PROFILER") == "{e2338988-38cc-48cd-a6b6-b441c31f34f1}" && Environment.GetEnvironmentVariable("COR_PROFILER") == "1"; #endif } } } } ``` Fix incorrect profiler environment variable name for .NET framework support
```c# using System; using System.Runtime.CompilerServices; namespace Mindscape.Raygun4Net { public static class APM { [ThreadStatic] private static bool _enabled = false; [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void Enable() { _enabled = true; } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void Disable() { _enabled = false; } public static bool IsEnabled { get { return _enabled; } } public static bool ProfilerAttached { get { #if NETSTANDARD1_6 || NETSTANDARD2_0 // Look for .NET CORE compatible Environment Variables return Environment.GetEnvironmentVariable("CORECLR_PROFILER") == "{e2338988-38cc-48cd-a6b6-b441c31f34f1}" && Environment.GetEnvironmentVariable("CORECLR_ENABLE_PROFILING") == "1"; #else // Look for .NET FRAMEWORK compatible Environment Variables return Environment.GetEnvironmentVariable("COR_PROFILER") == "{e2338988-38cc-48cd-a6b6-b441c31f34f1}" && Environment.GetEnvironmentVariable("COR_ENABLE_PROFILING") == "1"; #endif } } } } ```
10ac7175-9ff3-4f27-957b-daa60bf51eef
{ "language": "C#" }
```c# using System; namespace Tgstation.Server.Api.Rights { /// <summary> /// Rights for <see cref="Models.ConfigurationFile"/> /// </summary> [Flags] public enum ConfigurationRights : ulong { /// <summary> /// User has no rights /// </summary> None = 0, /// <summary> /// User may read files /// </summary> Read = 1, /// <summary> /// User may write files /// </summary> Write = 2, /// <summary> /// User may list files /// </summary> List = 3 } } ``` Fix ConfigurationsRights.List not being a power of 2
```c# using System; namespace Tgstation.Server.Api.Rights { /// <summary> /// Rights for <see cref="Models.ConfigurationFile"/> /// </summary> [Flags] public enum ConfigurationRights : ulong { /// <summary> /// User has no rights /// </summary> None = 0, /// <summary> /// User may read files /// </summary> Read = 1, /// <summary> /// User may write files /// </summary> Write = 2, /// <summary> /// User may list files /// </summary> List = 4 } } ```
07a1893f-f87b-4bf3-a2a4-08020a7f01e6
{ "language": "C#" }
```c# using System; using System.IO; using System.Linq; namespace DotVVM.Compiler { public static class Program { private static readonly string[] HelpOptions = new string[] { "--help", "-h", "-?", "/help", "/h", "/?" }; public static bool TryRun(FileInfo assembly, DirectoryInfo? projectDir) { var executor = ProjectLoader.GetExecutor(assembly.FullName); return executor.ExecuteCompile(assembly, projectDir, null); } public static int Main(string[] args) { if (args.Length != 2 || (args.Length == 1 && HelpOptions.Contains(args[0]))) { Console.Error.Write( @"Usage: DotVVM.Compiler <ASSEMBLY> <PROJECT_DIR> Arguments: <ASSEMBLY> Path to a DotVVM project assembly. <PROJECT_DIR> Path to a DotVVM project directory."); return 1; } var success = TryRun(new FileInfo(args[0]), new DirectoryInfo(args[1])); return success ? 0 : 1; } } } ``` Add a check for argument existence to the Compiler
```c# using System; using System.IO; using System.Linq; namespace DotVVM.Compiler { public static class Program { private static readonly string[] HelpOptions = new string[] { "--help", "-h", "-?", "/help", "/h", "/?" }; public static bool TryRun(FileInfo assembly, DirectoryInfo? projectDir) { var executor = ProjectLoader.GetExecutor(assembly.FullName); return executor.ExecuteCompile(assembly, projectDir, null); } public static int Main(string[] args) { // To minimize dependencies, this tool deliberately reinvents the wheel instead of using System.CommandLine. if (args.Length != 2 || (args.Length == 1 && HelpOptions.Contains(args[0]))) { Console.Error.Write( @"Usage: DotVVM.Compiler <ASSEMBLY> <PROJECT_DIR> Arguments: <ASSEMBLY> Path to a DotVVM project assembly. <PROJECT_DIR> Path to a DotVVM project directory."); return 1; } var assemblyFile = new FileInfo(args[0]); if (!assemblyFile.Exists) { Console.Error.Write($"Assembly '{assemblyFile}' does not exist."); return 1; } var projectDir = new DirectoryInfo(args[1]); if (!projectDir.Exists) { Console.Error.Write($"Project directory '{projectDir}' does not exist."); return 1; } var success = TryRun(assemblyFile, projectDir); return success ? 0 : 1; } } } ```
acb6fdc2-643c-43a1-b0de-8455b5a2b4e1
{ "language": "C#" }
```c# namespace FALM.Housekeeping.Constants { /// <summary> /// HkConstants /// </summary> public class HkConstants { /// <summary> /// Application /// </summary> public class Application { /// <summary>Name of the Application</summary> public const string Name = "F.A.L.M."; /// <summary>Alias of the Application</summary> public const string Alias = "FALM"; /// <summary>Icon of the Application</summary> public const string Icon = "icon-speed-gauge color-yellow"; /// <summary>Title of the Application</summary> public const string Title = "F.A.L.M. Housekeeping"; } /// <summary> /// Tree /// </summary> public class Tree { /// <summary>Name of the Tree</summary> public const string Name = "Housekeeping Tools"; /// <summary>Alias of the Tree</summary> public const string Alias = "housekeeping"; /// <summary>Icon of the Tree</summary> public const string Icon = "icon-umb-deploy"; /// <summary>Title of the Tree</summary> public const string Title = "Menu"; } /// <summary> /// Controller /// </summary> public class Controller { /// <summary>Alias of the Controller</summary> public const string Alias = "FALM"; } } }``` Change icon color to be consistent with other section icon colors
```c# namespace FALM.Housekeeping.Constants { /// <summary> /// HkConstants /// </summary> public class HkConstants { /// <summary> /// Application /// </summary> public class Application { /// <summary>Name of the Application</summary> public const string Name = "F.A.L.M."; /// <summary>Alias of the Application</summary> public const string Alias = "FALM"; /// <summary>Icon of the Application</summary> public const string Icon = "icon-speed-gauge"; /// <summary>Title of the Application</summary> public const string Title = "F.A.L.M. Housekeeping"; } /// <summary> /// Tree /// </summary> public class Tree { /// <summary>Name of the Tree</summary> public const string Name = "Housekeeping Tools"; /// <summary>Alias of the Tree</summary> public const string Alias = "housekeeping"; /// <summary>Icon of the Tree</summary> public const string Icon = "icon-umb-deploy"; /// <summary>Title of the Tree</summary> public const string Title = "Menu"; } /// <summary> /// Controller /// </summary> public class Controller { /// <summary>Alias of the Controller</summary> public const string Alias = "FALM"; } } }```
7909b1c0-e36f-48bf-bb88-7dc68912a36a
{ "language": "C#" }
```c# @using Cats.Models.Hubs @using Cats.Web.Hub.Helpers @using Telerik.Web.Mvc.UI @{ var usr = @Html.GetCurrentUser(); var mdl = new CurrentUserModel(usr); } <div align="right"> @{ string title = ""; if(ViewBag.Title != null) { title = ViewBag.Title; } } </div> <div class="row-fluid form-inline"> <h4 class="page-header">@Html.Translate(title) @Html.Label("Owner", mdl.Owner) - @Html.Label("WH", mdl.Name) @Html.Translate(" Hub ") @{ if(usr.UserAllowedHubs.Count > 1) { @Html.HubSelectionLink(Html.Translate("Change Warehouse"), Url.Action("HubList", "CurrentHub"), Html.Translate("Change Hub")) } } </h4> </div> ``` FIX CIT-785 Hide EDIT button for all users in hub
```c# @using Cats.Models.Hubs @using Cats.Web.Hub.Helpers @using Telerik.Web.Mvc.UI @{ var usr = @Html.GetCurrentUser(); var mdl = new CurrentUserModel(usr); } <div align="right"> @{ string title = ""; if(ViewBag.Title != null) { title = ViewBag.Title; } } </div> <div class="row-fluid form-inline"> <h4 class="page-header">@Html.Translate(title) @Html.Label("Owner", mdl.Owner) - @Html.Label("WH", mdl.Name) @Html.Translate(" Hub ") @*@{ if(usr.UserAllowedHubs.Count > 1) { @Html.HubSelectionLink(Html.Translate("Change Warehouse"), Url.Action("HubList", "CurrentHub"), Html.Translate("Change Hub")) } }*@ </h4> </div> ```
11a5e922-8e4b-42da-a3ff-56b499f8b329
{ "language": "C#" }
```c# @{ Layout = null; } <div class="container" style="padding-top: 50px;"> <div class="container"> <div class="panel panel-default"> <div class="panel-body"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th></th> <th>Forum Name</th> <th>Topics</th> <th>Posts</th> <th>Last Post</th> </tr> </thead> <tbody> <tr class="board-row" data-ng-repeat="board in boards"> <td></td> <td data-ng-click="openBoard(board.id)"><a data-ng-href="/#/forums/{{board.id}}">{{ board.name }}</a></td> <td>{{ board.totalTopics }}</td> <td>{{ board.totalPosts }}</td> <td> <div data-ng-show="board.lastTopicTitle != null"> <a href="/#/forums/{{ board.id }}/{{ board.lastTopicId }}">{{ board.lastTopicTitle }}</a> <div class="last-post-author">by {{ board.lastPostAuthor }}</div> </div> <div data-ng-show="board.lastTopicTitle == null"> <em>None</em> </div> </td> </tr> </tbody> </table> </div> </div> </div> </div> ``` Remove panel from index forum page for mobile devices
```c# @{ Layout = null; } <div class="container" style="padding-top: 50px;"> <div class="container"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th></th> <th>Forum Name</th> <th>Topics</th> <th>Posts</th> <th>Last Post</th> </tr> </thead> <tbody> <tr class="board-row" data-ng-repeat="board in boards"> <td></td> <td data-ng-click="openBoard(board.id)"><a data-ng-href="/#/forums/{{board.id}}">{{ board.name }}</a></td> <td>{{ board.totalTopics }}</td> <td>{{ board.totalPosts }}</td> <td> <div data-ng-show="board.lastTopicTitle != null"> <a href="/#/forums/{{ board.id }}/{{ board.lastTopicId }}">{{ board.lastTopicTitle }}</a> <div class="last-post-author">by {{ board.lastPostAuthor }}</div> </div> <div data-ng-show="board.lastTopicTitle == null"> <em>None</em> </div> </td> </tr> </tbody> </table> </div> </div> ```
535a353b-1227-4ca6-a1de-b0fc13e0b1dc
{ "language": "C#" }
```c# using System.Collections; using UnityEngine; using UnityEngine.Networking; public abstract class GameMessageBase : MessageBase { public GameObject NetworkObject; public GameObject[] NetworkObjects; protected IEnumerator WaitFor(NetworkInstanceId id) { int tries = 0; while ((NetworkObject = ClientScene.FindLocalObject(id)) == null) { if (tries++ > 10) { Debug.LogWarning($"{this} could not find object with id {id}"); yield break; } yield return YieldHelper.EndOfFrame; } } protected IEnumerator WaitFor(params NetworkInstanceId[] ids) { NetworkObjects = new GameObject[ids.Length]; while (!AllLoaded(ids)) { yield return YieldHelper.EndOfFrame; } } private bool AllLoaded(NetworkInstanceId[] ids) { for (int i = 0; i < ids.Length; i++) { GameObject obj = ClientScene.FindLocalObject(ids[i]); if (obj == null) { return false; } NetworkObjects[i] = obj; } return true; } } ``` Add case for waiting on an empty id
```c# using System.Collections; using UnityEngine; using UnityEngine.Networking; public abstract class GameMessageBase : MessageBase { public GameObject NetworkObject; public GameObject[] NetworkObjects; protected IEnumerator WaitFor(NetworkInstanceId id) { if (id.IsEmpty()) { Debug.LogError($"{this} tried to wait on an empty (0) id"); yield break; } int tries = 0; while ((NetworkObject = ClientScene.FindLocalObject(id)) == null) { if (tries++ > 10) { Debug.LogWarning($"{this} could not find object with id {id}"); yield break; } yield return YieldHelper.EndOfFrame; } } protected IEnumerator WaitFor(params NetworkInstanceId[] ids) { NetworkObjects = new GameObject[ids.Length]; while (!AllLoaded(ids)) { yield return YieldHelper.EndOfFrame; } } private bool AllLoaded(NetworkInstanceId[] ids) { for (int i = 0; i < ids.Length; i++) { GameObject obj = ClientScene.FindLocalObject(ids[i]); if (obj == null) { return false; } NetworkObjects[i] = obj; } return true; } } ```
422cdb07-54cb-4127-9ac1-252ac6b2747e
{ "language": "C#" }
```c# using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(DancingGoat.Startup))] namespace DancingGoat { public partial class Startup { public void Configuration(IAppBuilder app) { } } }``` Set TLS 1.2 as the default potocol
```c# using Microsoft.Owin; using Owin; using System.Net; [assembly: OwinStartupAttribute(typeof(DancingGoat.Startup))] namespace DancingGoat { public partial class Startup { public void Configuration(IAppBuilder app) { // .NET Framework 4.6.1 and lower does not support TLS 1.2 as the default protocol, but Delivery API requires it. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } } }```
917a0b64-f721-4602-87e0-fa740079e6f4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.Full { public class DefaultEngineConfiguration : IEngineConfiguration { public virtual int AllowedSecondsInKernel => 6000; public virtual IEnumerable<RunTargetEnum> RunTargets { get { yield return RunTargetEnum.Bochs; //yield return RunTargetEnum.VMware; //yield return RunTargetEnum.HyperV; //yield return RunTargetEnum.Qemu; } } public virtual bool RunWithGDB => true; public virtual bool StartBochsDebugGUI => true; public virtual bool DebugIL2CPU => false; public virtual string KernelPkg => String.Empty; public virtual TraceAssemblies TraceAssembliesLevel => TraceAssemblies.User; public virtual bool EnableStackCorruptionChecks => true; public virtual StackCorruptionDetectionLevel StackCorruptionDetectionLevel => StackCorruptionDetectionLevel.MethodFooters; public virtual DebugMode DebugMode => DebugMode.Source; public virtual IEnumerable<string> KernelAssembliesToRun { get { foreach (var xKernelType in TestKernelSets.GetKernelTypesToRun()) { yield return xKernelType.Assembly.Location; } } } } } ``` Disable GDB + Bochs GUI
```c# using System; using System.Collections.Generic; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.Full { public class DefaultEngineConfiguration : IEngineConfiguration { public virtual int AllowedSecondsInKernel => 6000; public virtual IEnumerable<RunTargetEnum> RunTargets { get { yield return RunTargetEnum.Bochs; //yield return RunTargetEnum.VMware; //yield return RunTargetEnum.HyperV; //yield return RunTargetEnum.Qemu; } } public virtual bool RunWithGDB => false; public virtual bool StartBochsDebugGUI => false; public virtual bool DebugIL2CPU => false; public virtual string KernelPkg => String.Empty; public virtual TraceAssemblies TraceAssembliesLevel => TraceAssemblies.User; public virtual bool EnableStackCorruptionChecks => true; public virtual StackCorruptionDetectionLevel StackCorruptionDetectionLevel => StackCorruptionDetectionLevel.MethodFooters; public virtual DebugMode DebugMode => DebugMode.Source; public virtual IEnumerable<string> KernelAssembliesToRun { get { foreach (var xKernelType in TestKernelSets.GetKernelTypesToRun()) { yield return xKernelType.Assembly.Location; } } } } } ```
1e5913ca-2ac5-423d-b925-808708c5e49c
{ "language": "C#" }
```c# using Moya.Extensions; using Xunit; namespace TestMoya.Extensions { public class StringExtensionsTests { [Fact] public void StringExtensionsFormatWithWorksWithWorksWithStrings() { const string Expected = "Hello world!"; var actual = "{0} {1}".FormatWith("Hello", "world!"); Assert.Equal(Expected, actual); } [Fact] public void StringExtensionsFormatWithWorksWithWorksWithIntegers() { const string Expected = "1 2 3 4"; var actual = "{0} {1} {2} {3}".FormatWith(1, 2, 3, 4); Assert.Equal(Expected, actual); } [Fact] public void StringExtensionsFormatWithWorksWithWorksWithIntegersAndStrings() { const string Expected = "1 2 Hello World!"; var actual = "{0} {1} {2} {3}".FormatWith(1, 2, "Hello", "World!"); Assert.Equal(Expected, actual); } } }``` Move usings inside namespace in stringextensionstests
```c# namespace TestMoya.Extensions { using Moya.Extensions; using Xunit; public class StringExtensionsTests { [Fact] public void StringExtensionsFormatWithWorksWithWorksWithStrings() { const string Expected = "Hello world!"; var actual = "{0} {1}".FormatWith("Hello", "world!"); Assert.Equal(Expected, actual); } [Fact] public void StringExtensionsFormatWithWorksWithWorksWithIntegers() { const string Expected = "1 2 3 4"; var actual = "{0} {1} {2} {3}".FormatWith(1, 2, 3, 4); Assert.Equal(Expected, actual); } [Fact] public void StringExtensionsFormatWithWorksWithWorksWithIntegersAndStrings() { const string Expected = "1 2 Hello World!"; var actual = "{0} {1} {2} {3}".FormatWith(1, 2, "Hello", "World!"); Assert.Equal(Expected, actual); } } }```
eac641e5-152a-425f-8d08-bb046a80cec0
{ "language": "C#" }
```c# using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NTumbleBit.BouncyCastle.Security { internal class SecureRandom : Random { public SecureRandom() { } public override int Next() { return RandomUtils.GetInt32(); } public override int Next(int maxValue) { throw new NotImplementedException(); } public override int Next(int minValue, int maxValue) { throw new NotImplementedException(); } public override void NextBytes(byte[] buffer) { RandomUtils.GetBytes(buffer); } } } ``` Fix crash caused by previous commit
```c# using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NTumbleBit.BouncyCastle.Security { internal class SecureRandom : Random { public SecureRandom() { } public override int Next() { return RandomUtils.GetInt32(); } public override int Next(int maxValue) { return (int)(RandomUtils.GetUInt32() % maxValue); } public override int Next(int minValue, int maxValue) { throw new NotImplementedException(); } public override void NextBytes(byte[] buffer) { RandomUtils.GetBytes(buffer); } } } ```
fc93d716-98b6-4502-9d06-0206cb19c2c1
{ "language": "C#" }
```c# @model LoginOrRegisterViewModel @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class="form-signin", @role="form"})) { <div class="form-group"> @Html.ValidationSummary(true) </div> <h2 class="form-signin-heading dark">Meld u alstublieft aan</h2> @Html.LabelFor(vm => vm.Login.UserName, new { @class="sr-only" }) @Html.TextBoxFor(vm => vm.Login.UserName, new { @class = "form-control", @type="email", @placeholder = "Gebruikersnaam of e-mailadres" }) @Html.LabelFor(vm => vm.Login.Password, new { @class="sr-only" }) @Html.PasswordFor(vm => vm.Login.Password, new { @class = "form-control", @placeholder = "Wachtwoord" }) <div class="checkbox dark"> <label class="pull-left"> @Html.CheckBoxFor(vm => vm.Login.RememberMe) Onthoud mij. </label> @Html.ActionLink("Wachtwoord vergeten?", "LostPassword", null, new { @class = "pull-right" }) <br/> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Inloggen</button> if(ViewData.ModelState.ContainsKey("registration")) { @ViewData.ModelState["registration"].Errors.First().ErrorMessage; } } ``` Remove wrong type for username and e-mail field
```c# @model LoginOrRegisterViewModel @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class="form-signin", @role="form"})) { <div class="form-group"> @Html.ValidationSummary(true) </div> <h2 class="form-signin-heading dark">Meld u alstublieft aan</h2> @Html.LabelFor(vm => vm.Login.UserName, new { @class="sr-only" }) @Html.TextBoxFor(vm => vm.Login.UserName, new { @class = "form-control", @placeholder = "Gebruikersnaam of e-mailadres" }) @Html.LabelFor(vm => vm.Login.Password, new { @class="sr-only" }) @Html.PasswordFor(vm => vm.Login.Password, new { @class = "form-control", @placeholder = "Wachtwoord" }) <div class="checkbox dark"> <label class="pull-left"> @Html.CheckBoxFor(vm => vm.Login.RememberMe) Onthoud mij. </label> @Html.ActionLink("Wachtwoord vergeten?", "LostPassword", null, new { @class = "pull-right" }) <br/> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Inloggen</button> if(ViewData.ModelState.ContainsKey("registration")) { @ViewData.ModelState["registration"].Errors.First().ErrorMessage; } } ```
e0bc88e2-9910-49d3-ad48-cc47321bc41c
{ "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 BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { public class BenchmarkBindableInstantiation { private Bindable<int> bindable; [GlobalSetup] public void GlobalSetup() => bindable = new Bindable<int>(); /// <summary> /// Creates an instance of the bindable directly by construction. /// </summary> [Benchmark(Baseline = true)] public Bindable<int> CreateInstanceViaConstruction() => new Bindable<int>(); /// <summary> /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type, object[])"/>. /// This used to be how <see cref="Bindable{T}.GetBoundCopy"/> creates an instance before binding, which has turned out to be inefficient in performance. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaActivatorWithParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), 0); /// <summary> /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type)"/>. /// More performant than <see cref="CreateInstanceViaActivatorWithParams"/>, due to not passing parameters to <see cref="Activator"/> during instance creation. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaActivatorWithoutParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), true); /// <summary> /// Creates an instance of the bindable via <see cref="IBindable.CreateInstance"/>. /// This is the current and most performant version used for <see cref="IBindable.GetBoundCopy"/>, as equally performant as <see cref="CreateInstanceViaConstruction"/>. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaBindableCreateInstance() => bindable.CreateInstance(); } } ``` Refactor benchmarks to only demonstrate what's needed
```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 BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { public class BenchmarkBindableInstantiation { [Benchmark(Baseline = true)] public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy(); [Benchmark] public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy(); private class BindableOld<T> : Bindable<T> { public BindableOld(T defaultValue = default) : base(defaultValue) { } protected internal override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value); } } } ```
d96a5478-3ac2-453c-b55c-2d104a1f5bdc
{ "language": "C#" }
```c# using Newtonsoft.Json; namespace SyncTrayzor.Syncthing.ApiClient { [JsonConverter(typeof(DefaultingStringEnumConverter))] public enum EventType { Unknown, Starting, StartupComplete, Ping, DeviceDiscovered, DeviceConnected, DeviceDisconnected, RemoteIndexUpdated, LocalIndexUpdated, ItemStarted, ItemFinished, // Not quite sure which it's going to be, so play it safe... MetadataChanged, ItemMetadataChanged, StateChanged, FolderRejected, DeviceRejected, ConfigSaved, DownloadProgress, FolderSummary, FolderCompletion, FolderErrors, FolderScanProgress, DevicePaused, DeviceResumed, LoginAttempt, ListenAddressChanged, } } ``` Add a couple of apparently missing events
```c# using Newtonsoft.Json; namespace SyncTrayzor.Syncthing.ApiClient { [JsonConverter(typeof(DefaultingStringEnumConverter))] public enum EventType { Unknown, Starting, StartupComplete, Ping, DeviceDiscovered, DeviceConnected, DeviceDisconnected, RemoteIndexUpdated, LocalIndexUpdated, ItemStarted, ItemFinished, // Not quite sure which it's going to be, so play it safe... MetadataChanged, ItemMetadataChanged, StateChanged, FolderRejected, DeviceRejected, ConfigSaved, DownloadProgress, FolderSummary, FolderCompletion, FolderErrors, FolderScanProgress, DevicePaused, DeviceResumed, LoginAttempt, ListenAddressChanged, RelayStateChanged, ExternalPortMappingChanged, } } ```
1538cea5-cf44-4590-9ee5-f31487608529
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Diagnostics; using System.IO; using System.Collections.Specialized; using System.Collections; namespace MICore { public class LocalTransport : PipeTransport { public LocalTransport() { } public override void InitStreams(LaunchOptions options, out StreamReader reader, out StreamWriter writer) { LocalLaunchOptions localOptions = (LocalLaunchOptions)options; Process proc = new Process(); proc.StartInfo.FileName = localOptions.MIDebuggerPath; proc.StartInfo.Arguments = "--interpreter=mi"; proc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(localOptions.MIDebuggerPath); InitProcess(proc, out reader, out writer); } protected override string GetThreadName() { return "MI.LocalTransport"; } } } ``` Add MI debugger working directory to PATH
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Diagnostics; using System.IO; using System.Collections.Specialized; using System.Collections; namespace MICore { public class LocalTransport : PipeTransport { public LocalTransport() { } public override void InitStreams(LaunchOptions options, out StreamReader reader, out StreamWriter writer) { LocalLaunchOptions localOptions = (LocalLaunchOptions)options; string miDebuggerDir = System.IO.Path.GetDirectoryName(localOptions.MIDebuggerPath); Process proc = new Process(); proc.StartInfo.FileName = localOptions.MIDebuggerPath; proc.StartInfo.Arguments = "--interpreter=mi"; proc.StartInfo.WorkingDirectory = miDebuggerDir; //GDB locally requires that the directory be on the PATH, being the working directory isn't good enough if (proc.StartInfo.EnvironmentVariables.ContainsKey("PATH")) { proc.StartInfo.EnvironmentVariables["PATH"] = proc.StartInfo.EnvironmentVariables["PATH"] + ";" + miDebuggerDir; } InitProcess(proc, out reader, out writer); } protected override string GetThreadName() { return "MI.LocalTransport"; } } } ```
19df8759-95e5-419a-a3e5-4649a13106e8
{ "language": "C#" }
```c# using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NQuery.UnitTests { [TestClass] public class SelectStarTests { [TestMethod] public void Binder_DisallowsSelectStarWithoutTables() { var syntaxTree = SyntaxTree.ParseQuery("SELECT *"); var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable(); var semanticModel = compilation.GetSemanticModel(); var diagnostics = semanticModel.GetDiagnostics().ToArray(); Assert.AreEqual(1, diagnostics.Length); Assert.AreEqual(DiagnosticId.MustSpecifyTableToSelectFrom, diagnostics[0].DiagnosticId); } [TestMethod] public void Binder_DisallowsSelectStarWithoutTables_UnlessInExists() { var syntaxTree = SyntaxTree.ParseQuery("SELECT 'Test' WHERE EXISTS (SELECT *)"); var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable(); var semanticModel = compilation.GetSemanticModel(); var diagnostics = semanticModel.GetDiagnostics().ToArray(); Assert.AreEqual(0, diagnostics.Length); } } }``` Rename SELECT * test cases to match naming convention
```c# using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NQuery.UnitTests { [TestClass] public class SelectStarTests { [TestMethod] public void SelectStar_Disallowed_WhenNoTablesSpecified() { var syntaxTree = SyntaxTree.ParseQuery("SELECT *"); var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable(); var semanticModel = compilation.GetSemanticModel(); var diagnostics = semanticModel.GetDiagnostics().ToArray(); Assert.AreEqual(1, diagnostics.Length); Assert.AreEqual(DiagnosticId.MustSpecifyTableToSelectFrom, diagnostics[0].DiagnosticId); } [TestMethod] public void SelectStar_Disallowed_WhenNoTablesSpecified_UnlessInExists() { var syntaxTree = SyntaxTree.ParseQuery("SELECT 'Test' WHERE EXISTS (SELECT *)"); var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable(); var semanticModel = compilation.GetSemanticModel(); var diagnostics = semanticModel.GetDiagnostics().ToArray(); Assert.AreEqual(0, diagnostics.Length); } } }```
d5f05693-211e-4247-8b2d-ff6f7b359a66
{ "language": "C#" }
```c# using System; using System.Linq; using Nancy; namespace Okanshi.Dashboard { public class SettingsModule : NancyModule { public SettingsModule(IConfiguration configuration) { Get["/settings"] = p => { var servers = configuration.GetAll().ToArray(); return View["settings.html", servers]; }; Post["/settings"] = p => { var name = Request.Form.Name; var url = Request.Form.url; var refreshRate = Convert.ToInt64(Request.Form.refreshRate.Value); var server = new OkanshiServer(name, url, refreshRate); configuration.Add(server); return Response.AsRedirect("/settings"); }; } } }``` Implement endpoint for remove instance
```c# using System; using System.Linq; using Nancy; namespace Okanshi.Dashboard { public class SettingsModule : NancyModule { public SettingsModule(IConfiguration configuration) { Get["/settings"] = p => { var servers = configuration.GetAll().ToArray(); return View["settings.html", servers]; }; Post["/settings"] = p => { var name = Request.Form.Name; var url = Request.Form.url; var refreshRate = Convert.ToInt64(Request.Form.refreshRate.Value); var server = new OkanshiServer(name, url, refreshRate); configuration.Add(server); return Response.AsRedirect("/settings"); }; Post["/settings/delete"] = p => { var name = (string)Request.Form.InstanceName; configuration.Remove(name); return Response.AsRedirect("/settings"); }; } } }```
ba719897-3485-4d60-a6ca-efc99918e6cf
{ "language": "C#" }
```c# @if (Model.DiscountedPrice != Model.Price) { <b class="inactive-price" style="text-decoration:line-through" title="@T("Was ${0}", Model.Price)">$@Model.Price</b> <b class="discounted-price" title="@T("Now ${0}", Model.DiscountedPrice)">$@Model.DiscountedPrice</b> <span class="discount-comment">@Model.DiscountComment</span> } else { <b>$@Model.Price</b> }``` Remove hard coded USD dollar symbol and use currency string formatting instead.
```c# @if (Model.DiscountedPrice != Model.Price) { <b class="inactive-price" style="text-decoration:line-through" title="@T("Was {0}", Model.Price.ToString("c"))">@Model.Price.ToString("c")</b> <b class="discounted-price" title="@T("Now {0}", Model.DiscountedPrice.ToString("c"))">@Model.DiscountedPrice.ToString("c")</b> <span class="discount-comment">@Model.DiscountComment</span> } else { <b>@Model.Price.ToString("c")</b> } ```
c13de7ea-b26c-4c1e-846a-f9bc2f715740
{ "language": "C#" }
```c# using S22.Xmpp.Client; using S22.Xmpp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using S22.Xmpp.Im; namespace XmppConsole { class Program { static void Main(string[] args) { try { using (var client = new XmppClient("something.com", "someone", "password")) { client.Connect(); client.Message += OnMessage; Console.WriteLine("Connected as " + client.Jid); string line; while ((line = Console.ReadLine()) != null) { Jid to = new Jid("something.com", "someone"); client.SendMessage(to, line, type: MessageType.Chat); } } } catch (Exception exc) { Console.WriteLine(exc.ToString()); } Console.WriteLine("Press any key to quit..."); Console.ReadLine(); } private static void OnMessage(object sender, MessageEventArgs e) { Console.WriteLine(e.Jid.Node + ": " + e.Message.Body); } } } ``` Put passwords in startup args
```c# using S22.Xmpp.Client; using S22.Xmpp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using S22.Xmpp.Im; namespace XmppConsole { class Program { static void Main(string[] args) { try { using (var client = new XmppClient(args[0], args[1], args[2])) { client.Connect(); client.SetStatus(Availability.Online); client.Message += OnMessage; Console.WriteLine("Connected as " + client.Jid); string line; while ((line = Console.ReadLine()) != null) { Jid to = new Jid("something.com", "someone"); client.SendMessage(to, line, type: MessageType.Chat); } client.SetStatus(Availability.Offline); } } catch (Exception exc) { Console.WriteLine(exc.ToString()); } Console.WriteLine("Press any key to quit..."); Console.ReadLine(); } private static void OnMessage(object sender, MessageEventArgs e) { Console.WriteLine(e.Jid.Node + ": " + e.Message.Body); } } } ```
54f60631-590a-43b3-bceb-bc3dac9fd654
{ "language": "C#" }
```c#  <div class="container"> <header class="container"> <h1>Sweet Water Revolver</h1> </header> </div>``` Remove the container class from the header, because it was redundant with its containing div.
```c#  <div class="container"> <header> <h1>Sweet Water Revolver</h1> </header> </div>```
ba0017f4-f0a4-4546-bc04-77228fc68bd7
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace PickemApp { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }``` Enable migrations on app start
```c# using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using PickemApp.Models; using PickemApp.Migrations; namespace PickemApp { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<PickemDBContext, Configuration>()); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }```
31860e40-6a1c-423a-8fde-19213667aa99
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Portfolio { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } } ``` Enable CF migrations on restart
```c# using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Portfolio { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Runs Code First database update on each restart... // handy for deploy via GitHub. #if !DEBUG var migrator = new DbMigrator(new Configuration()); migrator.Update(); #endif } } } ```
4c89451f-4825-401a-b7b3-dc3f2d5ee7ea
{ "language": "C#" }
```c# using System; using DemoDistributor.Endpoints.FileSystem; using DemoDistributor.Endpoints.Sharepoint; using Delivered; namespace DemoDistributor { internal class Program { private static void Main(string[] args) { //Configure the distributor var distributor = new Distributor<File, Vendor>(); //distributor.RegisterEndpointRepository(new FileSystemEndpointRepository()); distributor.RegisterEndpointRepository(new SharepointEndpointRepository()); distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService()); distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService()); distributor.MaximumConcurrentDeliveries(3); //Distribute a file to a vendor try { var task = distributor.DistributeAsync(FakeFile, FakeVendor); task.Wait(); Console.WriteLine("\nDistribution succeeded."); } catch(AggregateException aggregateException) { Console.WriteLine("\nDistribution failed."); foreach (var exception in aggregateException.Flatten().InnerExceptions) { Console.WriteLine($"* {exception.Message}"); } } Console.WriteLine("\nPress enter to exit."); Console.ReadLine(); } private static File FakeFile => new File { Name = @"test.pdf", Contents = new byte[1024] }; private static Vendor FakeVendor => new Vendor { Name = @"Mark's Pool Supplies" }; private static Vendor FakeVendor2 => new Vendor { Name = @"Kevin's Art Supplies" }; } } ``` Fix demo by uncommenting line accidentally left commented
```c# using System; using DemoDistributor.Endpoints.FileSystem; using DemoDistributor.Endpoints.Sharepoint; using Delivered; namespace DemoDistributor { internal class Program { private static void Main(string[] args) { //Configure the distributor var distributor = new Distributor<File, Vendor>(); distributor.RegisterEndpointRepository(new FileSystemEndpointRepository()); distributor.RegisterEndpointRepository(new SharepointEndpointRepository()); distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService()); distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService()); distributor.MaximumConcurrentDeliveries(3); //Distribute a file to a vendor try { var task = distributor.DistributeAsync(FakeFile, FakeVendor); task.Wait(); Console.WriteLine("\nDistribution succeeded."); } catch(AggregateException aggregateException) { Console.WriteLine("\nDistribution failed."); foreach (var exception in aggregateException.Flatten().InnerExceptions) { Console.WriteLine($"* {exception.Message}"); } } Console.WriteLine("\nPress enter to exit."); Console.ReadLine(); } private static File FakeFile => new File { Name = @"test.pdf", Contents = new byte[1024] }; private static Vendor FakeVendor => new Vendor { Name = @"Mark's Pool Supplies" }; private static Vendor FakeVendor2 => new Vendor { Name = @"Kevin's Art Supplies" }; } } ```
1547c84f-f0e1-4fdb-801b-7ec97873b813
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public abstract class BaseController : Controller { private static List<Player> playerList = new List<Player>(); public Player GetPlayer() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int id = Int32.Parse(idStr); Player player = SearchPlayer(id); if (player != null) return player; lock (playerList) { player = SearchPlayer(id); if (player != null) return player; Player newPlayer = Player.GetInstance(id); playerList.Add(newPlayer); return newPlayer; } } return null; } private Player SearchPlayer(int id) { if (!playerList.Any()) return null; foreach (Player listPlayer in playerList) { if (listPlayer.id == id) { return listPlayer; } } return null; } } } ``` Fix null players in player list.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public abstract class BaseController : Controller { private static List<Player> playerList = new List<Player>(); public Player GetPlayer() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int id = Int32.Parse(idStr); Player player = SearchPlayer(id); if (player != null) return player; lock (playerList) { player = SearchPlayer(id); if (player != null) return player; Player newPlayer = Player.GetInstance(id); if (newPlayer != null) playerList.Add(newPlayer); return newPlayer; } } return null; } private Player SearchPlayer(int id) { if (!playerList.Any()) return null; foreach (Player listPlayer in playerList) { if (listPlayer.id == id) { return listPlayer; } } return null; } } } ```
d55cb77c-cd2c-4e37-9a7d-27969754e471
{ "language": "C#" }
```c# using System.Windows.Controls; namespace PlantUmlEditor.View { public partial class DiagramEditorView : UserControl { public DiagramEditorView() { InitializeComponent(); } } } ``` Maintain focus on the text editor after saving.
```c# using System; using System.Windows.Controls; namespace PlantUmlEditor.View { public partial class DiagramEditorView : UserControl { public DiagramEditorView() { InitializeComponent(); ContentEditor.IsEnabledChanged += ContentEditor_IsEnabledChanged; } void ContentEditor_IsEnabledChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { // Maintain focus on the text editor. if ((bool)e.NewValue) Dispatcher.BeginInvoke(new Action(() => ContentEditor.Focus())); } } } ```
2b597cda-26dc-4694-81a4-d877e2362203
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Caliburn.Micro; namespace SharpGraphEditor.ViewModels { public class TextViewerViewModel : PropertyChangedBase { private string _text; private bool _canCopy; private bool _canCancel; private bool _isReadOnly; public TextViewerViewModel(string text, bool canCopy, bool canCancel, bool isReadOnly) { Text = text; CanCopy = CanCopy; CanCancel = canCancel; IsReadOnly = isReadOnly; } public void Ok(IClose closableWindow) { closableWindow.TryClose(true); } public void Cancel(IClose closableWindow) { closableWindow.TryClose(false); } public void CopyText() { Clipboard.SetText(Text); } public string Text { get { return _text; } set { _text = value; NotifyOfPropertyChange(() => Text); } } public bool CanCopy { get { return _canCopy; } set { _canCopy = value; NotifyOfPropertyChange(() => CanCopy); } } public bool CanCancel { get { return _canCancel; } set { _canCancel = value; NotifyOfPropertyChange(() => CanCancel); } } public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; NotifyOfPropertyChange(() => IsReadOnly); } } } } ``` Fix bug: "Copy" button don't show in TextView during saving
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Caliburn.Micro; namespace SharpGraphEditor.ViewModels { public class TextViewerViewModel : PropertyChangedBase { private string _text; private bool _canCopy; private bool _canCancel; private bool _isReadOnly; public TextViewerViewModel(string text, bool canCopy, bool canCancel, bool isReadOnly) { Text = text; CanCopy = canCopy; CanCancel = canCancel; IsReadOnly = isReadOnly; } public void Ok(IClose closableWindow) { closableWindow.TryClose(true); } public void Cancel(IClose closableWindow) { closableWindow.TryClose(false); } public void CopyText() { Clipboard.SetText(Text); } public string Text { get { return _text; } set { _text = value; NotifyOfPropertyChange(() => Text); } } public bool CanCopy { get { return _canCopy; } set { _canCopy = value; NotifyOfPropertyChange(() => CanCopy); } } public bool CanCancel { get { return _canCancel; } set { _canCancel = value; NotifyOfPropertyChange(() => CanCancel); } } public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; NotifyOfPropertyChange(() => IsReadOnly); } } } } ```
c6502f91-5e31-4a7a-bd95-850bb25f896b
{ "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 UIKit; namespace osu.iOS { public class Application { public static void Main(string[] args) { UIApplication.Main(args, null, "AppDelegate"); } } } ``` Fix iOS app entry for raw keyboard input
```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 UIKit; namespace osu.iOS { public class Application { public static void Main(string[] args) { UIApplication.Main(args, "GameUIApplication", "AppDelegate"); } } } ```
9d563bc9-27b7-4fc0-a1eb-c6e3f0b0e682
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using System.Web; namespace Mindscape.Raygun4Net.Breadcrumbs { internal class HttpBreadcrumbStorage : IRaygunBreadcrumbStorage { private const string ItemsKey = "Raygun.Breadcrumbs.Storage"; public IEnumerator<RaygunBreadcrumb> GetEnumerator() { return GetList().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Store(RaygunBreadcrumb breadcrumb) { GetList().Add(breadcrumb); } public void Clear() { GetList().Clear(); } private List<RaygunBreadcrumb> GetList() { SetupStorage(); return (List<RaygunBreadcrumb>) HttpContext.Current.Items[ItemsKey]; } private void SetupStorage() { if (HttpContext.Current != null && !HttpContext.Current.Items.Contains(ItemsKey)) { HttpContext.Current.Items[ItemsKey] = new List<RaygunBreadcrumb>(); } } } } ``` Return empty list if HttpContext.Current is null
```c# using System.Collections; using System.Collections.Generic; using System.Web; namespace Mindscape.Raygun4Net.Breadcrumbs { internal class HttpBreadcrumbStorage : IRaygunBreadcrumbStorage { private const string ItemsKey = "Raygun.Breadcrumbs.Storage"; public IEnumerator<RaygunBreadcrumb> GetEnumerator() { return GetList().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Store(RaygunBreadcrumb breadcrumb) { GetList().Add(breadcrumb); } public void Clear() { GetList().Clear(); } private List<RaygunBreadcrumb> GetList() { if (HttpContext.Current == null) { return new List<RaygunBreadcrumb>(); } SetupStorage(); return (List<RaygunBreadcrumb>) HttpContext.Current.Items[ItemsKey]; } private void SetupStorage() { if (HttpContext.Current != null && !HttpContext.Current.Items.Contains(ItemsKey)) { HttpContext.Current.Items[ItemsKey] = new List<RaygunBreadcrumb>(); } } } } ```
315e0453-a548-4ddd-a80d-2f04da5c7822
{ "language": "C#" }
```c# using RimWorld; using Verse; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { class RoomRoleWorker_ShrineRoom : RoomRoleWorker { public override float GetScore(Room room) { // I don't know if there should be some "If it's full of joy objects/work benches, *don't* classify it as // a Shrine - if you Shrine room wall gets broken down by a bug, this will probably push all the attached // rooms into the "Shrine Room" - is that a desired behaviour? Thing shrine = room.AllContainedThings.FirstOrDefault<Thing>(t => t is Building_Shrine); if (shrine == null) { return 0.0f; } else { return 9999.0f; } } } } ``` Fix ShrineRoom to always be current spawner
```c# using RimWorld; using Verse; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { class RoomRoleWorker_ShrineRoom : RoomRoleWorker { public override float GetScore(Room room) { // I don't know if there should be some "If it's full of joy objects/work benches, *don't* classify it as // a Shrine - if you Shrine room wall gets broken down by a bug, this will probably push all the attached // rooms into the "Shrine Room" - is that a desired behaviour? var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner; if (room.AllContainedThings.Contains<Thing>(shrine)) { return 9999.0f; } else { return 0.0f; } } } } ```
8e788b9d-86db-4af7-953e-195c45255e71
{ "language": "C#" }
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EOLib.Data.Protocol; using Microsoft.Practices.Unity; namespace EOLib.Net.Translators { public class PacketTranslatorContainer : IDependencyContainer { public void RegisterDependencies(IUnityContainer container) { container.RegisterType<IPacketTranslator<IInitializationData>, InitDataTranslator>(); } } } ``` Add IoC registration for login data translator
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EOLib.Data.Login; using EOLib.Data.Protocol; using Microsoft.Practices.Unity; namespace EOLib.Net.Translators { public class PacketTranslatorContainer : IDependencyContainer { public void RegisterDependencies(IUnityContainer container) { container.RegisterType<IPacketTranslator<IInitializationData>, InitDataTranslator>(); container.RegisterType<IPacketTranslator<IAccountLoginData>, AccountLoginPacketTranslator>(); } } } ```
312c7974-6e6f-49fd-9e5e-e4a3ca2e1f7a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Yio.Utilities; namespace Yio { public class Program { private static int _port { get; set; } public static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.Unicode; StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan); if (!File.Exists("appsettings.json")) { StartupUtilities.WriteFailure("configuration is missing"); Environment.Exit(1); } StartupUtilities.WriteInfo("setting port"); if(args == null || args.Length == 0) { _port = 5100; StartupUtilities.WriteSuccess("port set to " + _port + " (default)"); } else { _port = args[0] == null ? 5100 : Int32.Parse(args[0]); StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)"); } StartupUtilities.WriteInfo("starting App"); BuildWebHost(args).Run(); Console.ResetColor(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseUrls("http://0.0.0.0:" + _port.ToString() + "/") .UseStartup<Startup>() .Build(); } } ``` Fix port in arguments crashing app
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Yio.Utilities; namespace Yio { public class Program { private static int _port { get; set; } public static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.Unicode; StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan); if (!File.Exists("appsettings.json")) { StartupUtilities.WriteFailure("configuration is missing"); Environment.Exit(1); } StartupUtilities.WriteInfo("setting port"); if(args == null || args.Length == 0) { _port = 5100; StartupUtilities.WriteSuccess("port set to " + _port + " (default)"); } else { _port = args[0] == null ? 5100 : Int32.Parse(args[0]); StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)"); } StartupUtilities.WriteInfo("starting App"); BuildWebHost().Run(); Console.ResetColor(); } public static IWebHost BuildWebHost() => WebHost.CreateDefaultBuilder() .UseUrls("http://0.0.0.0:" + _port.ToString() + "/") .UseStartup<Startup>() .Build(); } } ```
16645dd4-f734-42fc-b447-f18f13b2a916
{ "language": "C#" }
```c# using System; namespace MarcelloDB.Helpers { internal class DataHelper { internal static void CopyData( Int64 sourceAddress, byte[] sourceData, Int64 targetAddress, byte[] targetData) { var lengthToCopy = sourceData.Length; var sourceIndex = 0; var targetIndex = 0; if (sourceAddress < targetAddress) { sourceIndex = (int)(targetAddress - sourceAddress); lengthToCopy = sourceData.Length - sourceIndex; } if (sourceAddress > targetAddress) { targetIndex = (int)(sourceAddress - targetAddress); lengthToCopy = targetData.Length - targetIndex; } //max length to copy to not overrun the target array lengthToCopy = Math.Min(lengthToCopy, targetData.Length - targetIndex); //max length to copy to not overrrude the source array lengthToCopy = Math.Min(lengthToCopy, sourceData.Length - sourceIndex); if (lengthToCopy > 0) { Array.Copy(sourceData, sourceIndex, targetData, targetIndex, lengthToCopy); } } } } ``` Fix integer overflow on large collection files
```c# using System; namespace MarcelloDB.Helpers { internal class DataHelper { internal static void CopyData( Int64 sourceAddress, byte[] sourceData, Int64 targetAddress, byte[] targetData) { Int64 lengthToCopy = sourceData.Length; Int64 sourceIndex = 0; Int64 targetIndex = 0; if (sourceAddress < targetAddress) { sourceIndex = (targetAddress - sourceAddress); lengthToCopy = sourceData.Length - sourceIndex; } if (sourceAddress > targetAddress) { targetIndex = (sourceAddress - targetAddress); lengthToCopy = targetData.Length - targetIndex; } //max length to copy to not overrun the target array lengthToCopy = Math.Min(lengthToCopy, targetData.Length - targetIndex); //max length to copy to not overrrun the source array lengthToCopy = Math.Min(lengthToCopy, sourceData.Length - sourceIndex); if (lengthToCopy > 0) { Array.Copy(sourceData, (int)sourceIndex, targetData, (int)targetIndex, (int)lengthToCopy); } } } } ```
190d8ee2-5f1d-46f2-b300-a39db46bb2bc
{ "language": "C#" }
```c# using System.Html.Media; using System.Runtime.CompilerServices; namespace System.Html { public partial class Navigator { [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozUserMedia || navigator.msGetUserMedia)({params}, {onsuccess})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess) {} [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozUserMedia || navigator.msGetUserMedia)({params}, {onsuccess}, {onerror})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess, Action<string> onerror) {} } }``` Fix navigator.getUserMedia webkit(TypeError: Illegal invocation) + moz(typo)
```c# using System.Html.Media; using System.Runtime.CompilerServices; namespace System.Html { public partial class Navigator { [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(navigator, {params}, {onsuccess})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess) {} [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(navigator, {params}, {onsuccess}, {onerror})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess, Action<string> onerror) {} } }```
bc6ae7fd-e92a-41cf-ae67-d1de3bebafb3
{ "language": "C#" }
```c# using System; using System.IO; using System.Collections; namespace DeviceMetadataInstallTool { /// <summary> /// see https://support.microsoft.com/en-us/kb/303974 /// </summary> class MetadataFinder { public System.Collections.Generic.List<String> Files = new System.Collections.Generic.List<String>(); public void SearchDirectory(string dir) { try { foreach (var d in Directory.GetDirectories(dir)) { foreach (var f in Directory.GetFiles(d, "*.devicemetadata-ms")) { Files.Add(f); } SearchDirectory(d); } } catch (System.Exception excpt) { Console.WriteLine(excpt.Message); } } } class Program { static void Main(string[] args) { var files = new System.Collections.Generic.List<String>(); //Console.WriteLine("Args size is {0}", args.Length); if (args.Length == 0) { var assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); var finder = new MetadataFinder(); finder.SearchDirectory(assemblyDir); files = finder.Files; } else { files.AddRange(files); } var store = new Sensics.DeviceMetadataInstaller.MetadataStore(); foreach (var fn in files) { var pkg = new Sensics.DeviceMetadataInstaller.MetadataPackage(fn); Console.WriteLine("{0} - {1} - Default locale: {2}", pkg.ExperienceGUID, pkg.ModelName, pkg.DefaultLocale); store.InstallPackage(pkg); } } } } ``` Use glob-recurse and fix the program when you pass it file names
```c# using System; using System.IO; using System.Collections; namespace DeviceMetadataInstallTool { class Program { static void Main(string[] args) { var files = new System.Collections.Generic.List<String>(); //Console.WriteLine("Args size is {0}", args.Length); if (args.Length == 0) { var assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); files = Sensics.DeviceMetadataInstaller.Util.GetMetadataFilesRecursive(assemblyDir); } else { files.AddRange(args); } var store = new Sensics.DeviceMetadataInstaller.MetadataStore(); foreach (var fn in files) { var pkg = new Sensics.DeviceMetadataInstaller.MetadataPackage(fn); Console.WriteLine("{0} - {1} - Default locale: {2}", pkg.ExperienceGUID, pkg.ModelName, pkg.DefaultLocale); store.InstallPackage(pkg); } } } } ```
9847159d-ad29-45d3-8e11-6530c8f32bcc
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE namespace osu.Framework.Platform.Linux { using Native; public class LinuxGameHost : DesktopGameHost { internal LinuxGameHost(string gameName, bool bindIPC = false) : base(gameName, bindIPC) { Window = new LinuxGameWindow(); Window.WindowStateChanged += (sender, e) => { if (Window.WindowState != OpenTK.WindowState.Minimized) OnActivated(); else OnDeactivated(); }; Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); } protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this); public override Clipboard GetClipboard() => new LinuxClipboard(); } } ``` Use more standard namespace formatting
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Platform.Linux.Native; namespace osu.Framework.Platform.Linux { public class LinuxGameHost : DesktopGameHost { internal LinuxGameHost(string gameName, bool bindIPC = false) : base(gameName, bindIPC) { Window = new LinuxGameWindow(); Window.WindowStateChanged += (sender, e) => { if (Window.WindowState != OpenTK.WindowState.Minimized) OnActivated(); else OnDeactivated(); }; Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); } protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this); public override Clipboard GetClipboard() => new LinuxClipboard(); } } ```
e09aa5c3-cd00-46f6-8092-b8c304d918e5
{ "language": "C#" }
```c# using System.IO; using OpenSage.Network; namespace OpenSage.Data.Sav { internal static class GameStateMap { internal static void Load(SaveFileReader reader, Game game) { reader.ReadVersion(2); var mapPath1 = reader.ReadAsciiString(); var mapPath2 = reader.ReadAsciiString(); var gameType = reader.ReadEnum<GameType>(); var mapSize = reader.BeginSegment(); // TODO: Delete this temporary map when ending the game. var mapPathInSaveFolder = Path.Combine( game.ContentManager.UserMapsFileSystem.RootDirectory, mapPath1); using (var mapOutputStream = File.OpenWrite(mapPathInSaveFolder)) { reader.ReadBytesIntoStream(mapOutputStream, (int)mapSize); } reader.EndSegment(); var unknown2 = reader.ReadUInt32(); // 586 var unknown3 = reader.ReadUInt32(); // 3220 if (gameType == GameType.Skirmish) { game.SkirmishManager = new LocalSkirmishManager(game); game.SkirmishManager.Settings.Load(reader); game.SkirmishManager.Settings.MapName = mapPath1; game.SkirmishManager.StartGame(); } else { game.StartSinglePlayerGame(mapPathInSaveFolder); } } } } ``` Fix map path for single player maps
```c# using System.IO; using OpenSage.Network; namespace OpenSage.Data.Sav { internal static class GameStateMap { internal static void Load(SaveFileReader reader, Game game) { reader.ReadVersion(2); var mapPath1 = reader.ReadAsciiString(); var mapPath2 = reader.ReadAsciiString(); var gameType = reader.ReadEnum<GameType>(); var mapSize = reader.BeginSegment(); // TODO: Delete this temporary map when ending the game. var mapPathInSaveFolder = Path.Combine( game.ContentManager.UserMapsFileSystem.RootDirectory, mapPath1); using (var mapOutputStream = File.OpenWrite(mapPathInSaveFolder)) { reader.ReadBytesIntoStream(mapOutputStream, (int)mapSize); } reader.EndSegment(); var unknown2 = reader.ReadUInt32(); // 586 var unknown3 = reader.ReadUInt32(); // 3220 if (gameType == GameType.Skirmish) { game.SkirmishManager = new LocalSkirmishManager(game); game.SkirmishManager.Settings.Load(reader); game.SkirmishManager.Settings.MapName = mapPath1; game.SkirmishManager.StartGame(); } else { game.StartSinglePlayerGame(mapPath1); } } } } ```
9a967d24-9c19-4887-bc0a-18e7fec78a83
{ "language": "C#" }
```c# namespace Papyrus { public static class EBookExtensions { } } ``` Add extension to verify mimetype.
```c# using System; using System.Threading.Tasks; using Windows.Storage; namespace Papyrus { public static class EBookExtensions { public static async Task<bool> VerifyMimetypeAsync(this EBook ebook) { var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype"); if (mimetypeFile == null) // Make sure file exists. return false; var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile); if (fileContents != "application/epub+zip") // Make sure file contents are correct. return false; return true; } } } ```
095ded39-92db-4152-878c-b908a356b220
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Net; using AppGet.Http; using NLog; namespace AppGet.PackageRepository { public class AppGetServerClient : IPackageRepository { private readonly IHttpClient _httpClient; private readonly Logger _logger; private readonly HttpRequestBuilder _requestBuilder; private const string API_ROOT = "https://appget.net/api/v1/"; public AppGetServerClient(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; _logger = logger; _requestBuilder = new HttpRequestBuilder(API_ROOT); } public PackageInfo GetLatest(string name) { _logger.Info("Getting package " + name); var request = _requestBuilder.Build("packages/{package}/latest"); request.AddSegment("package", name); try { var package = _httpClient.Get<PackageInfo>(request); return package.Resource; } catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.NotFound) { return null; } throw; } } public List<PackageInfo> Search(string term) { _logger.Info("Searching for " + term); var request = _requestBuilder.Build("packages"); request.UriBuilder.SetQueryParam("q", term.Trim()); var package = _httpClient.Get<List<PackageInfo>>(request); return package.Resource; } } }``` Use azure hosted server for now
```c# using System.Collections.Generic; using System.Net; using AppGet.Http; using NLog; namespace AppGet.PackageRepository { public class AppGetServerClient : IPackageRepository { private readonly IHttpClient _httpClient; private readonly Logger _logger; private readonly HttpRequestBuilder _requestBuilder; private const string API_ROOT = "https://appget.azurewebsites.net/v1/"; public AppGetServerClient(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; _logger = logger; _requestBuilder = new HttpRequestBuilder(API_ROOT); } public PackageInfo GetLatest(string name) { _logger.Info("Getting package " + name); var request = _requestBuilder.Build("packages/{package}/latest"); request.AddSegment("package", name); try { var package = _httpClient.Get<PackageInfo>(request); return package.Resource; } catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.NotFound) { return null; } throw; } } public List<PackageInfo> Search(string term) { _logger.Info("Searching for " + term); var request = _requestBuilder.Build("packages"); request.UriBuilder.SetQueryParam("q", term.Trim()); var package = _httpClient.Get<List<PackageInfo>>(request); return package.Resource; } } }```
7a0d051e-543e-4249-95f3-6a122013bc13
{ "language": "C#" }
```c# using NUnit.Framework; using System.Collections.Generic; namespace FunWithNewtonsoft { [TestFixture] public class ListTests { [Test] public void Deserialize_PartialList_ReturnsList() { // Assemble string json = @" {'Number':'1','Letter':'A'}, {'Number':'2','Letter':'B'}, {'Number':'3','Letter':'C'},"; // Act List<Data> actual = null; // Assert Assert.AreEqual(1, actual[0].Number); Assert.AreEqual("A", actual[0].Letter); Assert.AreEqual(2, actual[1].Number); Assert.AreEqual("B", actual[1].Letter); Assert.AreEqual(3, actual[2].Number); Assert.AreEqual("C", actual[2].Letter); } } }``` Add tests for json lists.
```c# using Newtonsoft.Json; using NUnit.Framework; using System.Collections.Generic; namespace FunWithNewtonsoft { [TestFixture] public class ListTests { [Test] public void DeserializeObject_JsonList_ReturnsList() { // Assemble string json = @" [ {'Number':'1','Letter':'A'}, {'Number':'2','Letter':'B'}, {'Number':'3','Letter':'C'} ]"; // Act List<Data> actual = JsonConvert.DeserializeObject<List<Data>>(json); // Assert Assert.AreEqual(1, actual[0].Number); Assert.AreEqual("A", actual[0].Letter); Assert.AreEqual(2, actual[1].Number); Assert.AreEqual("B", actual[1].Letter); Assert.AreEqual(3, actual[2].Number); Assert.AreEqual("C", actual[2].Letter); } [Test] public void DeserializeObject_MissingSquareBracesAroundJsonList_Throws() { // Assemble string json = @" {'Number':'1','Letter':'A'}, {'Number':'2','Letter':'B'}, {'Number':'3','Letter':'C'}"; // Act Assert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<List<Data>>(json)); } [Test] public void DeserializeObject_TrailingCommaAtEndOfJsonList_ReturnsList() { // Assemble string json = @" [ {'Number':'1','Letter':'A'}, {'Number':'2','Letter':'B'}, {'Number':'3','Letter':'C'}, ]"; // Act List<Data> actual = JsonConvert.DeserializeObject<List<Data>>(json); // Assert Assert.AreEqual(1, actual[0].Number); Assert.AreEqual("A", actual[0].Letter); Assert.AreEqual(2, actual[1].Number); Assert.AreEqual("B", actual[1].Letter); Assert.AreEqual(3, actual[2].Number); Assert.AreEqual("C", actual[2].Letter); } } }```
1f456308-20f2-4d10-a882-77a6f0523efd
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using GekkoAssembler.IntermediateRepresentation; namespace GekkoAssembler.Optimizers { public class IRMultiUnitOptimizer : IOptimizer { public IRCodeBlock Optimize(IRCodeBlock block) { var units = block.Units; var newUnits = units .Select(x => x is IRCodeBlock ? Optimize(x as IRCodeBlock) : x) .SelectMany(x => x is IRMultiUnit ? (x as IRMultiUnit).Inner : (IEnumerable<IIRUnit>)new[] { x }); return new IRCodeBlock(newUnits); } } } ``` Change the Order for Inlining Multi Units
```c# using System.Collections.Generic; using System.Linq; using GekkoAssembler.IntermediateRepresentation; namespace GekkoAssembler.Optimizers { public class IRMultiUnitOptimizer : IOptimizer { public IRCodeBlock Optimize(IRCodeBlock block) { var units = block.Units; var newUnits = units .SelectMany(x => x is IRMultiUnit ? (x as IRMultiUnit).Inner : (IEnumerable<IIRUnit>)new[] { x }) .Select(x => x is IRCodeBlock ? Optimize(x as IRCodeBlock) : x); return new IRCodeBlock(newUnits); } } } ```
dd58a4b4-e3e1-4f99-b0b6-e438a0931d1f
{ "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.Graphics.Sprites; using osu.Game.Overlays.Dialog; namespace osu.Game.Collections { public class DeleteCollectionDialog : PopupDialog { public DeleteCollectionDialog(BeatmapCollection collection, Action deleteAction) { HeaderText = "Confirm deletion of"; BodyText = collection.Name.Value; Icon = FontAwesome.Regular.TrashAlt; Buttons = new PopupDialogButton[] { new PopupDialogOkButton { Text = @"Yes. Go for it.", Action = deleteAction }, new PopupDialogCancelButton { Text = @"No! Abort mission!", }, }; } } } ``` Add count to deletion dialog
```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 Humanizer; using osu.Framework.Graphics.Sprites; using osu.Game.Overlays.Dialog; namespace osu.Game.Collections { public class DeleteCollectionDialog : PopupDialog { public DeleteCollectionDialog(BeatmapCollection collection, Action deleteAction) { HeaderText = "Confirm deletion of"; BodyText = $"{collection.Name.Value} ({"beatmap".ToQuantity(collection.Beatmaps.Count)})"; Icon = FontAwesome.Regular.TrashAlt; Buttons = new PopupDialogButton[] { new PopupDialogOkButton { Text = @"Yes. Go for it.", Action = deleteAction }, new PopupDialogCancelButton { Text = @"No! Abort mission!", }, }; } } } ```
2d4f6db2-347a-47f8-b537-c489c181a141
{ "language": "C#" }
```c# using UnityEngine; public class Planet : MonoBehaviour { [SerializeField] private float _radius; public float Radius { get { return _radius; } set { _radius = value; } } public float Permieter { get { return 2 * Mathf.PI * Radius; } } public void SampleOrbit2D( float angle, float distance, out Vector3 position, out Vector3 normal ) { // Polar to cartesian coordinates float x = Mathf.Cos( angle ) * distance; float y = Mathf.Sin( angle ) * distance; Vector3 dispalcement = new Vector3( x, 0, y ); Vector3 center = transform.position; position = center + dispalcement; normal = dispalcement.normalized; } } ``` Change orbit angles to degree
```c# using UnityEngine; public class Planet : MonoBehaviour { [SerializeField] private float _radius; public float Radius { get { return _radius; } set { _radius = value; } } public float Permieter { get { return 2 * Mathf.PI * Radius; } } public void SampleOrbit2D( float angle, float distance, out Vector3 position, out Vector3 normal ) { angle = angle * Mathf.Deg2Rad; // Polar to cartesian coordinates float x = Mathf.Cos( angle ) * distance; float y = Mathf.Sin( angle ) * distance; Vector3 dispalcement = new Vector3( x, 0, y ); Vector3 center = transform.position; position = center + dispalcement; normal = dispalcement.normalized; } } ```
9becbced-833b-495e-9417-295dd720640c
{ "language": "C#" }
```c# using System; namespace ExternalTemplates { /// <summary> /// Default generator options. /// </summary> public class GeneratorOptions : IGeneratorOptions { /// <summary> /// Gets the path relative to the web root where the templates are stored. /// Default is "/Content/templates". /// </summary> public string VirtualPath { get; set; } /// <summary> /// Gets the extension of the templates. /// Default is ".tmpl.html". /// </summary> public string Extension { get; set; } /// <summary> /// Gets the post string to add to the end of the script tag's id following its name. /// Default is "-tmpl". /// </summary> public string PostString { get; set; } } }``` Add the defaults for GeneratorOptions
```c# using System; namespace ExternalTemplates { /// <summary> /// Default generator options. /// </summary> public class GeneratorOptions : IGeneratorOptions { /// <summary> /// Gets the path relative to the web root where the templates are stored. /// Default is "/Content/templates". /// </summary> public string VirtualPath { get; set; } = "/Content/templates"; /// <summary> /// Gets the extension of the templates. /// Default is ".tmpl.html". /// </summary> public string Extension { get; set; } = ".tmpl.html"; /// <summary> /// Gets the post string to add to the end of the script tag's id following its name. /// Default is "-tmpl". /// </summary> public string PostString { get; set; } = "-tmpl"; } }```
254affdd-bb13-4502-81dd-f07fab3b55e3
{ "language": "C#" }
```c# using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.MySql { public class MySqlQuoter : GenericQuoter { public override string OpenQuote { get { return "`"; } } public override string CloseQuote { get { return "`"; } } public override string QuoteValue(object value) { return base.QuoteValue(value).Replace(@"\", @"\\"); } public override string FromTimeSpan(System.TimeSpan value) { return System.String.Format("{0}{1}:{2}:{3}.{4}{0}" , ValueQuote , value.Hours + (value.Days * 24) , value.Minutes , value.Seconds , value.Milliseconds); } } } ``` Fix MySql do not support Milliseconds
```c# using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.MySql { public class MySqlQuoter : GenericQuoter { public override string OpenQuote { get { return "`"; } } public override string CloseQuote { get { return "`"; } } public override string QuoteValue(object value) { return base.QuoteValue(value).Replace(@"\", @"\\"); } public override string FromTimeSpan(System.TimeSpan value) { return System.String.Format("{0}{1:00}:{2:00}:{3:00}{0}" , ValueQuote , value.Hours + (value.Days * 24) , value.Minutes , value.Seconds); } } } ```
544a13a7-ccec-4f62-ac03-15acfae99d95
{ "language": "C#" }
```c# using System; using Dominion.Rules; using Dominion.Rules.Activities; using Dominion.Rules.CardTypes; namespace Dominion.Cards.Actions { public class Chancellor : Card, IActionCard { public Chancellor() : base(3) { } public void Play(TurnContext context) { context.MoneyToSpend += 2; context.AddEffect(new ChancellorEffect()); } public class ChancellorEffect : CardEffectBase { public override void Resolve(TurnContext context) { _activities.Add(new ChancellorActivity(context.Game.Log, context.ActivePlayer, "Do you wish to put your deck into your discard pile?")); } public class ChancellorActivity : YesNoChoiceActivity { public ChancellorActivity(IGameLog log, Player player, string message) : base(log, player, message) { } public override void Execute(bool choice) { if (choice) { Log.LogMessage("{0} put his deck in his discard pile", Player.Name); this.Player.Deck.MoveAll(this.Player.Discards); } } } } } }``` Stop chancellor from prompting the player when they have no cards in their deck.
```c# using System; using Dominion.Rules; using Dominion.Rules.Activities; using Dominion.Rules.CardTypes; namespace Dominion.Cards.Actions { public class Chancellor : Card, IActionCard { public Chancellor() : base(3) { } public void Play(TurnContext context) { context.MoneyToSpend += 2; context.AddEffect(new ChancellorEffect()); } public class ChancellorEffect : CardEffectBase { public override void Resolve(TurnContext context) { if(context.ActivePlayer.Deck.CardCount > 0) _activities.Add(new ChancellorActivity(context.Game.Log, context.ActivePlayer, "Do you wish to put your deck into your discard pile?")); } public class ChancellorActivity : YesNoChoiceActivity { public ChancellorActivity(IGameLog log, Player player, string message) : base(log, player, message) { } public override void Execute(bool choice) { if (choice) { Log.LogMessage("{0} put his deck in his discard pile", Player.Name); this.Player.Deck.MoveAll(this.Player.Discards); } } } } } }```
f9c42ae7-716b-433a-9ad8-afd1211d750b
{ "language": "C#" }
```c# using System; using System.Collections.Specialized; using Xunit; namespace GV.AspNet.Configuration.ConfigurationManager.UnitTests { public class AppSettingsConfigurationProviderTests { [Theory] [InlineData("Key1", "Value1")] [InlineData("Key2", "Value2")] public void LoadsKeyValuePairsFromAppSettings(string key, string value) { var appSettings = new NameValueCollection { { key, value } }; var source = new AppSettingsConfigurationProvider(appSettings, ":", string.Empty); source.Load(); string outValue; Assert.True(source.TryGet(key, out outValue)); Assert.Equal(value, outValue); } } }``` Add support for custom key delimiter
```c# using System; using System.Collections.Specialized; using Microsoft.Extensions.Configuration; using Xunit; namespace GV.AspNet.Configuration.ConfigurationManager.UnitTests { public class AppSettingsConfigurationProviderTests { public class Load { [Theory] [InlineData("", "Value")] [InlineData("Key", "Value")] public void AddsAppSettings(string key, string value) { var appSettings = new NameValueCollection { { key, value } }; var keyDelimiter = Constants.KeyDelimiter; var keyPrefix = string.Empty; var source = new AppSettingsConfigurationProvider(appSettings, keyDelimiter, keyPrefix); source.Load(); string configurationValue; Assert.True(source.TryGet(key, out configurationValue)); Assert.Equal(value, configurationValue); } [Theory] [InlineData("Parent.Key", "", "Parent.Key", "Value")] [InlineData("Parent.Key", ".", "Parent:Key", "Value")] public void ReplacesKeyDelimiter(string appSettingsKey, string keyDelimiter, string configurationKey, string value) { var appSettings = new NameValueCollection { { appSettingsKey, value } }; var keyPrefix = string.Empty; var source = new AppSettingsConfigurationProvider(appSettings, keyDelimiter, keyPrefix); source.Load(); string configurationValue; Assert.True(source.TryGet(configurationKey, out configurationValue)); Assert.Equal(value, configurationValue); } } } }```
69630bdb-763d-436a-bb3f-c78c882a79b6
{ "language": "C#" }
```c# using System.Linq; using Bugsnag.Payload; using Xunit; namespace Bugsnag.Tests.Payload { public class ExceptionTests { [Fact] public void CorrectNumberOfExceptions() { var exception = new System.Exception("oh noes!"); var exceptions = new Exceptions(exception, 5); Assert.Single(exceptions); } [Fact] public void IncludeInnerExceptions() { var innerException = new System.Exception(); var exception = new System.Exception("oh noes!", innerException); var exceptions = new Exceptions(exception, 5); Assert.Equal(2, exceptions.Count()); } } } ``` Test for aggregate exception handling
```c# using System.Linq; using System.Threading.Tasks; using Bugsnag.Payload; using Xunit; namespace Bugsnag.Tests.Payload { public class ExceptionTests { [Fact] public void CorrectNumberOfExceptions() { var exception = new System.Exception("oh noes!"); var exceptions = new Exceptions(exception, 5); Assert.Single(exceptions); } [Fact] public void IncludeInnerExceptions() { var innerException = new System.Exception(); var exception = new System.Exception("oh noes!", innerException); var exceptions = new Exceptions(exception, 5); Assert.Equal(2, exceptions.Count()); } [Fact] public void HandleAggregateExceptions() { Exceptions exceptions = null; var exceptionsToThrow = new[] { new System.Exception(), new System.DllNotFoundException() }; var tasks = exceptionsToThrow.Select(e => Task.Run(() => { throw e; })).ToArray(); try { Task.WaitAll(tasks); } catch (System.Exception exception) { exceptions = new Exceptions(exception, 0); } var results = exceptions.ToArray(); Assert.Contains(results, exception => exception.ErrorClass == "System.DllNotFoundException"); Assert.Contains(results, exception => exception.ErrorClass == "System.Exception"); Assert.Contains(results, exception => exception.ErrorClass == "System.AggregateException"); } } } ```