doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
70c28f96-ee61-48ee-a7e6-782c26b4ded1
{ "language": "C#" }
```c# /*Problem 3. Check for a Play Card Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A. Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. Examples: character Valid card sign? 5 yes 1 no Q yes q no P no 10 yes 500 no */ using System; class CheckPlayCard { static void Main() { Console.Title = "Check for a Play Card"; //Changing the title of the console. Console.Write("Please, enter a play card sign to check if it is valid: "); string cardSign = Console.ReadLine(); switch (cardSign) { case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "10": case "J": case "Q": case "K": case "A": Console.WriteLine("\nValid card sign?\nyes"); break; default: Console.WriteLine("\nValid card sign?\nno"); break; } Console.ReadKey(); // Keeping the console opened. } }``` Update to Problem 3. Check for a Play Card
```c# /*Problem 3. Check for a Play Card Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A. Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. Examples: character Valid card sign? 5 yes 1 no Q yes q no P no 10 yes 500 no */ using System; class CheckPlayCard { static void Main() { Console.Title = "Check for a Play Card"; //Changing the title of the console. Console.Write("Please, enter a play card sign to check if it is valid: "); string cardSign = Console.ReadLine(); switch (cardSign) { case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "10": case "J": case "Q": case "K": case "A": Console.WriteLine("\r\nValid card sign?\r\nyes"); break; default: Console.WriteLine("\r\nValid card sign?\r\nno"); break; } Console.ReadKey(); // Keeping the console opened. } }```
c8d7af49-66d6-4073-be2b-489f9df82433
{ "language": "C#" }
```c# using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; namespace Bit.ViewModel.Implementations { public class BitHttpClientHandler : HttpClientHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // ToDo: // Current-Time-Zone // Desired-Time-Zone // Client-App-Version // Client-Culture // Client-Route // Client-Theme // Client-Debug-Mode // System-Language // Client-Sys-Language // Client-Platform // ToDo: Use IDeviceService & IDateTimeProvider request.Headers.Add("Client-Type", "Xamarin"); if (Device.Idiom != TargetIdiom.Unsupported) request.Headers.Add("Client-Screen-Size", Device.Idiom == TargetIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet"); request.Headers.Add("Client-Date-Time", DefaultDateTimeProvider.Current.GetCurrentUtcDateTime().UtcDateTime.ToString("o")); request.Headers.Add("X-CorrelationId", Guid.NewGuid().ToString()); request.Headers.Add("Bit-Client-Type", "CS-Client"); return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } } } ``` Use AndroidClientHandler for android & NSUrlSessionHandler for iOS by default in bit cs client
```c# using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; namespace Bit.ViewModel.Implementations { public class BitHttpClientHandler : #if Android Xamarin.Android.Net.AndroidClientHandler #elif iOS NSUrlSessionHandler #else HttpClientHandler #endif { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // ToDo: // Current-Time-Zone // Desired-Time-Zone // Client-App-Version // Client-Culture // Client-Route // Client-Theme // Client-Debug-Mode // System-Language // Client-Sys-Language // Client-Platform // ToDo: Use IDeviceService & IDateTimeProvider request.Headers.Add("Client-Type", "Xamarin"); if (Device.Idiom != TargetIdiom.Unsupported) request.Headers.Add("Client-Screen-Size", Device.Idiom == TargetIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet"); request.Headers.Add("Client-Date-Time", DefaultDateTimeProvider.Current.GetCurrentUtcDateTime().UtcDateTime.ToString("o")); request.Headers.Add("X-CorrelationId", Guid.NewGuid().ToString()); request.Headers.Add("Bit-Client-Type", "CS-Client"); return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } } } ```
e833690d-94c0-44fd-bbef-110d2f21fcbe
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using Csla.Core; using Csla; namespace DataBindingApp { [Serializable()] public class ListObject : BusinessListBase<ListObject, ListObject.DataObject> { [Serializable()] public class DataObject : BusinessBase<DataObject> { private int _ID; private string _data; private int _number; public int Number { get { return _number; } set { _number = value; } } public string Data { get { return _data; } set { _data = value; } } public int ID { get { return _ID; } set { _ID = value; } } protected override object GetIdValue() { return _ID; } public DataObject(string data, int number) { this.MarkAsChild(); _data = data; _number = number; this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(DataObject_PropertyChanged); } public void DataObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { Console.WriteLine("Property has changed"); } } private ListObject() { } public static ListObject GetList() { ListObject list = new ListObject(); for (int i = 0; i < 5; i++) { list.Add(new DataObject("element" + i, i)); } return list; } } } ``` Make sure GetIdValue returns a unique value per object.
```c# using System; using System.Collections.Generic; using System.Text; using Csla.Core; using Csla; namespace DataBindingApp { [Serializable()] public class ListObject : BusinessListBase<ListObject, ListObject.DataObject> { [Serializable()] public class DataObject : BusinessBase<DataObject> { private int _ID; private string _data; private int _number; public int Number { get { return _number; } set { _number = value; } } public string Data { get { return _data; } set { _data = value; } } public int ID { get { return _ID; } set { _ID = value; } } protected override object GetIdValue() { return _number; } public DataObject(string data, int number) { this.MarkAsChild(); _data = data; _number = number; this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(DataObject_PropertyChanged); } public void DataObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { Console.WriteLine("Property has changed"); } } private ListObject() { } public static ListObject GetList() { ListObject list = new ListObject(); for (int i = 0; i < 5; i++) { list.Add(new DataObject("element" + i, i)); } return list; } } } ```
d37ab25e-2fd7-41e2-ba95-c63d9218c8b1
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.WriteLine(@")] public class Vaca : Migration { public override void Up() {"); writer.Write($" Create.Table(\"{tableName}\")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() {"); writer.Write($" Delete.Table(\"{tableName}\");"); writer.WriteLine(@" } } }"); } } }``` Fix namespace & class name
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { const string format = "yyyyMMddHHmmss"; writer.WriteLine(@"namespace Migrations {"); writer.WriteLine($" [Migration(\"{DateTime.Now.ToString(format)}\")]"); writer.Write($" public class {tableName}Migration : Migration"); writer.WriteLine(@" { public override void Up() {"); writer.Write($" Create.Table(\"{tableName}\")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() {"); writer.Write($" Delete.Table(\"{tableName}\");"); writer.WriteLine(@" } } }"); } } }```
5c4b814e-b104-4450-b8c3-728e7ab1e06d
{ "language": "C#" }
```c# using System; using System.Linq; using ExRam.Gremlinq.Core.Tests; using FluentAssertions; using Xunit; using static ExRam.Gremlinq.Core.GremlinQuerySource; namespace ExRam.Gremlinq.Providers.CosmosDb.Tests { public class GroovySerializationTest : GroovySerializationTest<CosmosDbGroovyGremlinQueryElementVisitor> { [Fact] public void Limit_overflow() { g .V() .Limit((long)int.MaxValue + 1) .Invoking(x => new CosmosDbGroovyGremlinQueryElementVisitor().Visit(x)) .Should() .Throw<ArgumentOutOfRangeException>(); } [Fact] public void Where_property_array_intersects_empty_array2() { g .V<User>() .Where(t => t.PhoneNumbers.Intersect(new string[0]).Any()) .Should() .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())") .WithParameters("User"); } } } ``` Bring back integration test for CosmosDb.
```c# using System; using System.Linq; using ExRam.Gremlinq.Core.Tests; using FluentAssertions; using Xunit; using static ExRam.Gremlinq.Core.GremlinQuerySource; namespace ExRam.Gremlinq.Providers.CosmosDb.Tests { public class GroovySerializationTest : GroovySerializationTest<CosmosDbGroovyGremlinQueryElementVisitor> { [Fact] public void Limit_overflow() { g .V() .Limit((long)int.MaxValue + 1) .Invoking(x => new CosmosDbGroovyGremlinQueryElementVisitor().Visit(x)) .Should() .Throw<ArgumentOutOfRangeException>(); } [Fact] public void Where_property_array_intersects_empty_array() { g .V<User>() .Where(t => t.PhoneNumbers.Intersect(new string[0]).Any()) .Should() .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())") .WithParameters("User"); } [Fact] public void Where_property_is_contained_in_empty_enumerable() { var enumerable = Enumerable.Empty<int>(); g .V<User>() .Where(t => enumerable.Contains(t.Age)) .Should() .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())") .WithParameters("User"); } } } ```
aa22ef3f-7a17-4c81-9428-5dd9c435ce4d
{ "language": "C#" }
```c# using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using Octokit.Internal; namespace Octokit { static class EnumExtensions { [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] internal static string ToParameter(this Enum prop) { if (prop == null) return null; var propString = prop.ToString(); var member = prop.GetType().GetMember(propString).FirstOrDefault(); if (member == null) return null; var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false) .Cast<ParameterAttribute>() .FirstOrDefault(); return attribute != null ? attribute.Value : propString.ToLowerInvariant(); } } } ``` Add back in the reflection namespace
```c# using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using Octokit.Internal; namespace Octokit { static class EnumExtensions { [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] internal static string ToParameter(this Enum prop) { if (prop == null) return null; var propString = prop.ToString(); var member = prop.GetType().GetMember(propString).FirstOrDefault(); if (member == null) return null; var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false) .Cast<ParameterAttribute>() .FirstOrDefault(); return attribute != null ? attribute.Value : propString.ToLowerInvariant(); } } } ```
bd286a58-b8c8-4732-85fa-d4a7fcfb6269
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace MailChimp.Net.Api { class PostHelpers { public static string PostJson(string url, string data) { var bytes = Encoding.Default.GetBytes(data); using (var client = new WebClient()) { client.Headers.Add("Content-Type", "application/json"); var response = client.UploadData(url, "POST", bytes); return Encoding.Default.GetString(response); } } } } ``` Update default encoding to utf8 for supporting non-us symbols
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace MailChimp.Net.Api { class PostHelpers { public static string PostJson(string url, string data) { var bytes = Encoding.UTF8.GetBytes(data); using (var client = new WebClient()) { client.Headers.Add("Content-Type", "application/json"); var response = client.UploadData(url, "POST", bytes); return Encoding.Default.GetString(response); } } } } ```
131cf709-1180-4a2b-8d8b-6ab66d07a70c
{ "language": "C#" }
```c# using Discord.Commands; using Modix.Services.AutoCodePaste; using System.Threading.Tasks; namespace Modix.Modules { [Name("Code Paste"), Summary("Paste some code to the internet.")] public class CodePasteModule : ModuleBase { private CodePasteService _service; public CodePasteModule(CodePasteService service) { _service = service; } [Command("paste"), Summary("Paste the rest of your message to the internet, and return the URL.")] public async Task Run([Remainder] string code) { string url = await _service.UploadCode(Context.Message, code); var embed = _service.BuildEmbed(Context.User, code, url); await ReplyAsync(Context.User.Mention, false, embed); await Context.Message.DeleteAsync(); } } } ``` Handle hastebin failure in the CodePaste module
```c# using Discord.Commands; using Modix.Services.AutoCodePaste; using System.Net; using System.Threading.Tasks; namespace Modix.Modules { [Name("Code Paste"), Summary("Paste some code to the internet.")] public class CodePasteModule : ModuleBase { private CodePasteService _service; public CodePasteModule(CodePasteService service) { _service = service; } [Command("paste"), Summary("Paste the rest of your message to the internet, and return the URL.")] public async Task Run([Remainder] string code) { string url = null; string error = null; try { url = await _service.UploadCode(Context.Message, code); } catch (WebException ex) { url = null; error = ex.Message; } if (url != null) { var embed = _service.BuildEmbed(Context.User, code, url); await ReplyAsync(Context.User.Mention, false, embed); await Context.Message.DeleteAsync(); } else { await ReplyAsync(error); } } } } ```
c67d5d7d-d627-4826-8a4f-534d73943c58
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), 5); Assert.AreEqual(ClassLibrary1.Class1.ReturnSix(), 6); } [TestMethod] public void ShouldFail() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), ClassLibrary1.Class1.ReturnSix()); } } } ``` Fix failing test ... by removing it
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), 5); Assert.AreEqual(ClassLibrary1.Class1.ReturnSix(), 6); } } } ```
7aac2e5e-e335-4478-ac24-f5ca59fcafee
{ "language": "C#" }
```c# using System; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class P : ConverterBase { public P(Converter converter) : base(converter) { Converter.Register("p", this); } public override string Convert(HtmlNode node) { var indentation = IndentationFor(node); return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}{Environment.NewLine}"; } private static string IndentationFor(HtmlNode node) { var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count(); return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node ? new string(' ', length * 4) : Environment.NewLine + Environment.NewLine; } } } ``` Fix to convert paragraph tag with single carriage return
```c# using System; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class P : ConverterBase { public P(Converter converter) : base(converter) { Converter.Register("p", this); } public override string Convert(HtmlNode node) { var indentation = IndentationFor(node); return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}"; } private static string IndentationFor(HtmlNode node) { var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count(); return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node ? new string(' ', length * 4) : Environment.NewLine; } } } ```
65c4f6f9-6e6c-45ca-997e-ce004fe6a3ce
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.TeamFoundation.Authentication.Test { /// <summary> /// A class to test <see cref="Configuration"/>. /// </summary> [TestClass] public class ConfigurationTests { [TestMethod] public void ParseGitConfig_Simple() { const string input = @" [core] autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } private static Dictionary<string, string> TestParseGitConfig(string input) { var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (var sr = new StringReader(input)) { Configuration.ParseGitConfig(sr, values); } return values; } } } ``` Add test to verify overwriting of values.
```c# using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.TeamFoundation.Authentication.Test { /// <summary> /// A class to test <see cref="Configuration"/>. /// </summary> [TestClass] public class ConfigurationTests { [TestMethod] public void ParseGitConfig_Simple() { const string input = @" [core] autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } [TestMethod] public void ParseGitConfig_OverwritesValues() { // http://thedailywtf.com/articles/What_Is_Truth_0x3f_ const string input = @" [core] autocrlf = true autocrlf = FileNotFound autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } private static Dictionary<string, string> TestParseGitConfig(string input) { var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (var sr = new StringReader(input)) { Configuration.ParseGitConfig(sr, values); } return values; } } } ```
63fcbb40-12bc-4211-a6b4-fadce5621784
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(TestExtensionErrorHandler))] [Export(typeof(IExtensionErrorHandler))] internal class TestExtensionErrorHandler : IExtensionErrorHandler { private List<Exception> _exceptions = new List<Exception>(); public void HandleError(object sender, Exception exception) { if (exception is ArgumentOutOfRangeException && ((ArgumentOutOfRangeException)exception).ParamName == "span") { // TODO: this is known bug 655591, fixed by Jack in changeset 931906 // Remove this workaround once the fix reaches the DP branch and we all move over. return; } _exceptions.Add(exception); } public ICollection<Exception> GetExceptions() { // We'll clear off our list, so that way we don't report this for other tests var newExceptions = _exceptions; _exceptions = new List<Exception>(); return newExceptions; } } } ``` Delete workaround for a long-fixed editor bug
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(TestExtensionErrorHandler))] [Export(typeof(IExtensionErrorHandler))] internal class TestExtensionErrorHandler : IExtensionErrorHandler { private List<Exception> _exceptions = new List<Exception>(); public void HandleError(object sender, Exception exception) { _exceptions.Add(exception); } public ICollection<Exception> GetExceptions() { // We'll clear off our list, so that way we don't report this for other tests var newExceptions = _exceptions; _exceptions = new List<Exception>(); return newExceptions; } } } ```
4fd38488-5a7e-4079-b103-dc3ada017a86
{ "language": "C#" }
```c# using KeyPay.DomainModels.V2.PayRun; using RestSharp; namespace KeyPay.ApiFunctions.V2 { public class PayRunDeductionFunction : BaseFunction { public PayRunDeductionFunction(ApiRequestExecutor api) : base(api) { } public DeductionsResponse List(int businessId, int payRunId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions"); } public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions) { return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST); } } }``` Add function to get deductions from a payrun for a specific employee
```c# using KeyPay.DomainModels.V2.PayRun; using RestSharp; namespace KeyPay.ApiFunctions.V2 { public class PayRunDeductionFunction : BaseFunction { public PayRunDeductionFunction(ApiRequestExecutor api) : base(api) { } public DeductionsResponse List(int businessId, int payRunId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions"); } public DeductionsResponse List(int businessId, int payRunId, int employeeId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions/" + employeeId); } public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions) { return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST); } } }```
92fdd1fb-82e5-484c-afae-4d07db77d16b
{ "language": "C#" }
```c# using System.Web; using System.Web.Optimization; namespace ClubChallengeBeta { 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*")); // 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-*")); //blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js", "~/Scripts/blueimp-gallery.js", "~/Scripts/bootstrap-image-gallery.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/blueimp-gallery.css", "~/Content/bootstrap-image-gallery.css", "~/Content/bootstrap-social.css", "~/Content/font-awesome.css", "~/Content/ionicons.css", "~/Content/site.css")); } } } ``` Change app to use minified files
```c# using System.Web; using System.Web.Optimization; namespace ClubChallengeBeta { 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}.min.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // 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-*")); //blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.min.js", "~/Scripts/respond.min.js", "~/Scripts/blueimp-gallery.min.js", "~/Scripts/bootstrap-image-gallery.min.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.min.css", "~/Content/blueimp-gallery.min.css", "~/Content/bootstrap-image-gallery.min.css", "~/Content/bootstrap-social.css", "~/Content/font-awesome.css", "~/Content/ionicons.min.css", "~/Content/site.css")); } } } ```
0e7fff71-0c76-4a47-a473-be0249266551
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Scalar.Resolver { public interface IScalarResolver { object Execute(); } public interface IScalarResolver<T> : IScalarResolver { T Execute(); } } ``` Remove warning about hidden versus new
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Scalar.Resolver { public interface IScalarResolver { object Execute(); } public interface IScalarResolver<T> : IScalarResolver { new T Execute(); } } ```
6793efe8-afc5-4b0b-8174-43e9d7946e62
{ "language": "C#" }
```c# using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Watchdog { /// <summary> /// See <see cref="IActiveAssemblyDeleter"/> for Windows systems /// </summary> sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter { /// <summary> /// Set a file located at <paramref name="path"/> to be deleted on reboot /// </summary> /// <param name="path">The file to delete on reboot</param> [ExcludeFromCodeCoverage] static void DeleteFileOnReboot(string path) { if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot)) throw new Win32Exception(Marshal.GetLastWin32Error()); } /// <inheritdoc /> public void DeleteActiveAssembly(string assemblyPath) { if (assemblyPath == null) throw new ArgumentNullException(nameof(assemblyPath)); //Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file //Also append the long path prefix just in case we're running on .NET framework var tmpLocation = String.Concat(@"\\?\", assemblyPath, Guid.NewGuid()); File.Move(assemblyPath, tmpLocation); DeleteFileOnReboot(tmpLocation); } } } ``` Remove windows long filename prefix
```c# using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Watchdog { /// <summary> /// See <see cref="IActiveAssemblyDeleter"/> for Windows systems /// </summary> sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter { /// <summary> /// Set a file located at <paramref name="path"/> to be deleted on reboot /// </summary> /// <param name="path">The file to delete on reboot</param> [ExcludeFromCodeCoverage] static void DeleteFileOnReboot(string path) { if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot)) throw new Win32Exception(Marshal.GetLastWin32Error()); } /// <inheritdoc /> public void DeleteActiveAssembly(string assemblyPath) { if (assemblyPath == null) throw new ArgumentNullException(nameof(assemblyPath)); //Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file var tmpLocation = String.Concat(assemblyPath, Guid.NewGuid()); File.Move(assemblyPath, tmpLocation); DeleteFileOnReboot(tmpLocation); } } } ```
99446bcb-eeb9-43e1-a7e5-3de8a7270990
{ "language": "C#" }
```c# using MarcelloDB.Collections; using MarcelloDB.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace MarcelloDB.uwp { public class Platform : IPlatform { public Storage.IStorageStreamProvider CreateStorageStreamProvider(string rootPath) { return new FileStorageStreamProvider(GetFolderForPath(rootPath)); } StorageFolder GetFolderForPath(string path) { var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask(); getFolderTask.ConfigureAwait(false); getFolderTask.Wait(); return getFolderTask.Result; } } } ``` Fix namespace issue in uwp
```c# using MarcelloDB.Collections; using MarcelloDB.Platform; using MarcelloDB.Storage; using MarcelloDB.uwp.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace MarcelloDB.uwp { public class Platform : IPlatform { public IStorageStreamProvider CreateStorageStreamProvider(string rootPath) { return new FileStorageStreamProvider(GetFolderForPath(rootPath)); } StorageFolder GetFolderForPath(string path) { var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask(); getFolderTask.ConfigureAwait(false); getFolderTask.Wait(); return getFolderTask.Result; } } } ```
28b6916f-bd0e-4c2b-8669-8d47d3c8d009
{ "language": "C#" }
```c# using System.Collections.Generic; namespace BankFileParsers { public class BaiDetail { public string TransactionDetail { get; private set; } public List<string> DetailContinuation { get; internal set; } public BaiDetail(string line) { TransactionDetail = line; DetailContinuation = new List<string>(); } } }``` Add new method to overwrite TransactionDetail line with a new string.
```c# using System.Collections.Generic; namespace BankFileParsers { public class BaiDetail { public string TransactionDetail { get; private set; } public List<string> DetailContinuation { get; internal set; } public BaiDetail(string line) { TransactionDetail = line; DetailContinuation = new List<string>(); } /// <summary> /// Overwrite the TransactionDetail line with a new string /// </summary> /// <param name="line">New string to overwrite with</param> public void SetTransactionDetail(string line) { TransactionDetail = line; } } }```
f923120a-b6db-427f-a0aa-bbd21fe7773d
{ "language": "C#" }
```c# using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")] public class Action_Patrol : Action { public override void Act(StateController controller) { Act(controller as Enemy_StateController); } public void Act(Enemy_StateController controller) { Patrol(controller); } private void Patrol(Enemy_StateController controller) { controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position; controller.navMeshAgent.Resume (); if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending) { controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count; } } }``` Replace obsolete NavMeshAgent interface fot he newer one
```c# using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")] public class Action_Patrol : Action { public override void Act(StateController controller) { Act(controller as Enemy_StateController); } public void Act(Enemy_StateController controller) { Patrol(controller); } private void Patrol(Enemy_StateController controller) { controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position; controller.navMeshAgent.isStopped = false; if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending) { controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count; } } }```
398c9007-2c12-4eed-8288-13ede26d89c7
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")] [assembly: AssemblyDescription("")] ``` Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
```c# using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")] ```
71bec767-f9f9-4da8-a89f-4d70fb84ef46
{ "language": "C#" }
```c# using OpenQA.Selenium; using System; namespace Atata { // TODO: Review IWebElementExtensions class. Remove unused methods. public static class IWebElementExtensions { public static WebElementExtendedSearchContext Try(this IWebElement element) { return new WebElementExtendedSearchContext(element); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout) { return new WebElementExtendedSearchContext(element, timeout); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval) { return new WebElementExtendedSearchContext(element, timeout, retryInterval); } public static bool HasContent(this IWebElement element, string content) { return element.Text.Contains(content); } public static string GetValue(this IWebElement element) { return element.GetAttribute("value"); } public static IWebElement FillInWith(this IWebElement element, string text) { element.Clear(); if (!string.IsNullOrEmpty(text)) element.SendKeys(text); return element; } } } ``` Add HasClass extension method for IWebElement
```c# using System; using System.Linq; using OpenQA.Selenium; namespace Atata { // TODO: Review IWebElementExtensions class. Remove unused methods. public static class IWebElementExtensions { public static WebElementExtendedSearchContext Try(this IWebElement element) { return new WebElementExtendedSearchContext(element); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout) { return new WebElementExtendedSearchContext(element, timeout); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval) { return new WebElementExtendedSearchContext(element, timeout, retryInterval); } public static bool HasContent(this IWebElement element, string content) { return element.Text.Contains(content); } public static bool HasClass(this IWebElement element, string className) { return element.GetAttribute("class").Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Contains(className); } public static string GetValue(this IWebElement element) { return element.GetAttribute("value"); } public static IWebElement FillInWith(this IWebElement element, string text) { element.Clear(); if (!string.IsNullOrEmpty(text)) element.SendKeys(text); return element; } } } ```
bb96c5e0-139a-4602-ad3d-5c7e2ebfe3dd
{ "language": "C#" }
```c# using System; using Xamarin.Forms; namespace XamarinTest { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { TelemetryManager.TrackEvent ("My Shared Event"); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } } ``` Use public interface in test app
```c# using System; using Xamarin.Forms; namespace XamarinTest { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { TelemetryManager.TrackEvent ("My Shared Event"); ApplicationInsights.RenewSessionWithId ("MySession"); ApplicationInsights.SetUserId ("Christoph"); TelemetryManager.TrackMetric ("My custom metric", 2.2); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } } ```
0b915d14-ba29-436b-bff9-fe6aaf971b63
{ "language": "C#" }
```c# using NLog; using Sandbox; using Torch.API; using Torch.Managers; using VRage.Dedicated.RemoteAPI; namespace Torch.Server.Managers { public class RemoteAPIManager : Manager { /// <inheritdoc /> public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance) { } /// <inheritdoc /> public override void Attach() { if (MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey)) { var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey); LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}"); } base.Attach(); } } }``` Fix remote API load order
```c# using NLog; using Sandbox; using Torch.API; using Torch.Managers; using VRage.Dedicated.RemoteAPI; namespace Torch.Server.Managers { public class RemoteAPIManager : Manager { /// <inheritdoc /> public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance) { } /// <inheritdoc /> public override void Attach() { Torch.GameStateChanged += TorchOnGameStateChanged; base.Attach(); } /// <inheritdoc /> public override void Detach() { Torch.GameStateChanged -= TorchOnGameStateChanged; base.Detach(); } private void TorchOnGameStateChanged(MySandboxGame game, TorchGameState newstate) { if (newstate == TorchGameState.Loading && MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey)) { var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey); LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}"); } } } }```
6a366bcd-c073-4c19-9655-ec7b7f978973
{ "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.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security; using WcfTestBridgeCommon; namespace WcfService.TestResources { internal class BasicAuthResource : EndpointResource<WcfUserNameService, IWcfCustomUserNameService> { protected override string Address { get { return "https-basic"; } } protected override string Protocol { get { return BaseAddressResource.Https; } } protected override int GetPort(ResourceRequestContext context) { return context.BridgeConfiguration.BridgeHttpsPort; } protected override Binding GetBinding() { var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; return binding; } private ServiceCredentials GetServiceCredentials() { var serviceCredentials = new ServiceCredentials(); serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator(); return serviceCredentials; } protected override void ModifyBehaviors(ServiceDescription desc) { base.ModifyBehaviors(desc); desc.Behaviors.Remove<ServiceCredentials>(); desc.Behaviors.Add(GetServiceCredentials()); } } } ``` Fix test failure when BasicAuth tests were first to run
```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.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security; using WcfService.CertificateResources; using WcfTestBridgeCommon; namespace WcfService.TestResources { internal class BasicAuthResource : EndpointResource<WcfUserNameService, IWcfCustomUserNameService> { protected override string Address { get { return "https-basic"; } } protected override string Protocol { get { return BaseAddressResource.Https; } } protected override int GetPort(ResourceRequestContext context) { return context.BridgeConfiguration.BridgeHttpsPort; } protected override Binding GetBinding() { var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; return binding; } private ServiceCredentials GetServiceCredentials() { var serviceCredentials = new ServiceCredentials(); serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator(); return serviceCredentials; } protected override void ModifyBehaviors(ServiceDescription desc) { base.ModifyBehaviors(desc); desc.Behaviors.Remove<ServiceCredentials>(); desc.Behaviors.Add(GetServiceCredentials()); } protected override void ModifyHost(ServiceHost serviceHost, ResourceRequestContext context) { // Ensure the https certificate is installed before this endpoint resource is used CertificateResourceHelpers.EnsureSslPortCertificateInstalled(context.BridgeConfiguration); base.ModifyHost(serviceHost, context); } } } ```
68a05d5d-f2dd-4280-b3b9-374fcad1a54d
{ "language": "C#" }
```c# using System; namespace FluentAssertions.Common { internal static class Guard { public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName) { if (obj is null) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName, string message) { if (obj is null) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName, string message) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName, message); } } /// <summary> /// Workaround to make dotnet_code_quality.null_check_validation_methods work /// https://github.com/dotnet/roslyn-analyzers/issues/3451#issuecomment-606690452 /// </summary> [AttributeUsage(AttributeTargets.Parameter)] private sealed class ValidatedNotNullAttribute : Attribute { } } } ``` Add guard methods for Enum Argument OutOfRange check
```c# using System; namespace FluentAssertions.Common { internal static class Guard { public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName) { if (obj is null) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName, string message) { if (obj is null) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName, string message) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsOutOfRange<T>([ValidatedNotNull] T value, string paramName) where T : Enum { if (!Enum.IsDefined(typeof(T), value)) { throw new ArgumentOutOfRangeException(paramName); } } public static void ThrowIfArgumentIsOutOfRange<T>([ValidatedNotNull] T value, string paramName, string message) where T : Enum { if (!Enum.IsDefined(typeof(T), value)) { throw new ArgumentOutOfRangeException(paramName, message); } } /// <summary> /// Workaround to make dotnet_code_quality.null_check_validation_methods work /// https://github.com/dotnet/roslyn-analyzers/issues/3451#issuecomment-606690452 /// </summary> [AttributeUsage(AttributeTargets.Parameter)] private sealed class ValidatedNotNullAttribute : Attribute { } } } ```
dd0df46e-4210-489d-94d8-d310c5e12bce
{ "language": "C#" }
```c# @model IEnumerable<RightpointLabs.Pourcast.Web.Areas.Admin.Models.TapModel> @{ ViewBag.Title = "Index"; } <h2>Taps</h2> @foreach (var tap in Model) { <div class="col-lg-6"> <h3>@tap.Name</h3> @if (null == tap.Keg) { <h4>No Keg On Tap</h4> <hr /> } else { <h4>@tap.Keg.BeerName</h4> <p> Amount of Beer Remaining: @tap.Keg.AmountOfBeerRemaining <br /> Percent Left: @tap.Keg.PercentRemaining <br /> </p> } <p> @Html.ActionLink("Edit", "Edit", new {id = tap.Id}) </p> </div> } <p> | @Html.ActionLink("Back to List", "Index") </p> ``` Add fake pour buttons in admin
```c# @model IEnumerable<RightpointLabs.Pourcast.Web.Areas.Admin.Models.TapModel> @{ ViewBag.Title = "Index"; } <h2>Taps</h2> @foreach (var tap in Model) { <div class="col-lg-6"> <h3>@tap.Name</h3> @if (null == tap.Keg) { <h4>No Keg On Tap</h4> <hr /> } else { <h4>@tap.Keg.BeerName</h4> <p> Amount of Beer Remaining: @tap.Keg.AmountOfBeerRemaining <br /> Percent Left: @tap.Keg.PercentRemaining <br /> </p> } <p> @Html.ActionLink("Edit", "Edit", new {id = tap.Id}, new { @class = "btn"}) @if (null != tap.Keg) { <a class="btn btn-pour" data-tap-id="@tap.Id" href="#">Pour</a> } </p> </div> } <p> | @Html.ActionLink("Back to List", "Index") </p> @section scripts { <script type="text/javascript"> $(function () { $(".btn-pour").each(function() { var $t = $(this); var tapId = $t.attr("data-tap-id"); var timer = null; var start = null; $t.mousedown(function () { $.getJSON("/api/tap/" + tapId + "/StartPour"); start = new Date().getTime(); timer = setInterval(function () { $.getJSON("/api/tap/" + tapId + "/Pouring?volume=" + ((new Date().getTime() - start) / 500)); }, 250); }); $t.mouseup(function () { clearInterval(timer); $.getJSON("/api/tap/" + tapId + "/StopPour?volume=" + ((new Date().getTime() - start) / 500)); }); }); }); </script> }```
7a33d732-d346-4689-907c-c08f8eb894b3
{ "language": "C#" }
```c# using System.Text.RegularExpressions; namespace MarekMotykaBot.ExtensionsMethods { public static class StringExtensions { public static string RemoveRepeatingChars(this string inputString) { string newString = string.Empty; char[] charArray = inputString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (string.IsNullOrEmpty(newString)) newString += charArray[i].ToString(); else if (newString[newString.Length - 1] != charArray[i]) newString += charArray[i].ToString(); } return newString; } public static string RemoveEmojis(this string inputString) { return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-\']+", "", RegexOptions.Compiled); } public static string RemoveEmotes(this string inputString) { return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled); } public static string RemoveEmojisAndEmotes(this string inputString) { return inputString.RemoveEmotes().RemoveEmojis(); } } }``` Fix regex pattern in removing emotes.
```c# using System.Text.RegularExpressions; namespace MarekMotykaBot.ExtensionsMethods { public static class StringExtensions { public static string RemoveRepeatingChars(this string inputString) { string newString = string.Empty; char[] charArray = inputString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (string.IsNullOrEmpty(newString)) newString += charArray[i].ToString(); else if (newString[newString.Length - 1] != charArray[i]) newString += charArray[i].ToString(); } return newString; } public static string RemoveEmojis(this string inputString) { return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-]+", "", RegexOptions.Compiled); } public static string RemoveEmotes(this string inputString) { return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled); } public static string RemoveEmojisAndEmotes(this string inputString) { return inputString.RemoveEmotes().RemoveEmojis(); } } }```
8b4237a7-1d5a-40b6-acb5-729c8089805e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace api { public class CommaDelimitedArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelMetadata.IsEnumerableType) { var key = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(key).ToString(); if (!string.IsNullOrWhiteSpace(value)) { var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Result = ModelBindingResult.Success(typedValues); } else { Console.WriteLine("string was empty"); // change this line to null if you prefer nulls to empty arrays bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0)); } return Task.CompletedTask; } Console.WriteLine("Not enumerable"); return Task.CompletedTask; } } } ``` Add input binder to allow for comma-separated list inputs for API routes
```c# using System; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace api { public class CommaDelimitedArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelMetadata.IsEnumerableType) { var key = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(key).ToString(); if (!string.IsNullOrWhiteSpace(value)) { var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Result = ModelBindingResult.Success(typedValues); } else { Console.WriteLine("string was empty"); // change this line to null if you prefer nulls to empty arrays bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0)); } return Task.CompletedTask; } Console.WriteLine("Not enumerable"); return Task.CompletedTask; } } } ```
1e315dd0-63fc-42b6-8e18-541ff6ac15c5
{ "language": "C#" }
```c# using Core; using StructureMap; using System.Diagnostics; using Xunit; namespace Tests { public class TroubleshootingTests { [Fact] public void ShowBuildPlan() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var buildPlan = container.Model.For<IService>() .Default .DescribeBuildPlan(); var expectedBuildPlan = @"PluginType: Core.IService Lifecycle: Transient new Service() "; Assert.Equal(expectedBuildPlan, buildPlan); } [Fact] public void WhatDoIHave() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var whatDoIHave = container.WhatDoIHave(); Trace.Write(whatDoIHave); } } } ``` Modify WhatDoIHave to show expected result
```c# using Core; using StructureMap; using Xunit; namespace Tests { public class TroubleshootingTests { [Fact] public void ShowBuildPlan() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var buildPlan = container.Model.For<IService>() .Default .DescribeBuildPlan(); var expectedBuildPlan = @"PluginType: Core.IService Lifecycle: Transient new Service() "; Assert.Equal(expectedBuildPlan, buildPlan); } [Fact] public void WhatDoIHave() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var whatDoIHave = container.WhatDoIHave(); var expectedWhatDoIHave = @" =================================================================================================== PluginType Namespace Lifecycle Description Name --------------------------------------------------------------------------------------------------- Func<TResult> System Transient Open Generic Template for Func<> (Default) --------------------------------------------------------------------------------------------------- Func<T, TResult> System Transient Open Generic Template for Func<,> (Default) --------------------------------------------------------------------------------------------------- IContainer StructureMap Singleton Object: StructureMap.Container (Default) --------------------------------------------------------------------------------------------------- IService Core Transient Core.Service (Default) --------------------------------------------------------------------------------------------------- Lazy<T> System Transient Open Generic Template for Func<> (Default) ==================================================================================================="; Assert.Equal(expectedWhatDoIHave, whatDoIHave); } } } ```
515c0660-b3ea-46a3-be80-3e838ba62799
{ "language": "C#" }
```c# namespace Mollie.Api.Models.Payment { public static class PaymentMethod { public const string Bancontact = "bancontact"; public const string BankTransfer = "banktransfer"; public const string Belfius = "belfius"; public const string CreditCard = "creditcard"; public const string DirectDebit = "directdebit"; public const string Eps = "eps"; public const string GiftCard = "giftcard"; public const string Giropay = "giropay"; public const string Ideal = "ideal"; public const string IngHomePay = "inghomepay"; public const string Kbc = "kbc"; public const string PayPal = "paypal"; public const string PaySafeCard = "paysafecard"; public const string Sofort = "sofort"; public const string Refund = "refund"; public const string KlarnaPayLater = "klarnapaylater"; public const string KlarnaSliceIt = "klarnasliceit"; public const string Przelewy24 = "przelewy24"; public const string ApplePay = "applepay"; public const string MealVoucher = "mealvoucher"; } }``` Add support for the new upcoming in3 payment method
```c# namespace Mollie.Api.Models.Payment { public static class PaymentMethod { public const string Bancontact = "bancontact"; public const string BankTransfer = "banktransfer"; public const string Belfius = "belfius"; public const string CreditCard = "creditcard"; public const string DirectDebit = "directdebit"; public const string Eps = "eps"; public const string GiftCard = "giftcard"; public const string Giropay = "giropay"; public const string Ideal = "ideal"; public const string IngHomePay = "inghomepay"; public const string Kbc = "kbc"; public const string PayPal = "paypal"; public const string PaySafeCard = "paysafecard"; public const string Sofort = "sofort"; public const string Refund = "refund"; public const string KlarnaPayLater = "klarnapaylater"; public const string KlarnaSliceIt = "klarnasliceit"; public const string Przelewy24 = "przelewy24"; public const string ApplePay = "applepay"; public const string MealVoucher = "mealvoucher"; public const string In3 = "in3"; } }```
8939ca30-c59e-4dc2-99fc-e03b6ad09925
{ "language": "C#" }
```c# using Rescuer.Management.Rescuers; namespace Rescuer.Management.Controller { public class RescuerController : IRescuerController { private readonly IRescuerFactory _factory; public RescuerController(IRescuerFactory factory) { _factory = factory; } public IRescuer[] IntializeRescuers(string[] monitoredEntities) { var rescuers = new IRescuer[monitoredEntities.Length]; for (int i = 0; i < rescuers.Length; i++) { rescuers[i] = _factory.Create(); rescuers[i].Connect(monitoredEntities[i]); } return rescuers; } public void DoWork(IRescuer[] rescuers) { for (int i = 0; i < rescuers.Length; i++) { rescuers[i].MonitorAndRescue(); } } } }``` Handle empty entity name in rescuer
```c# using System; using System.Text; using Rescuer.Management.Rescuers; namespace Rescuer.Management.Controller { public class RescuerController : IRescuerController { private readonly IRescuerFactory _factory; public RescuerController(IRescuerFactory factory) { _factory = factory; } public IRescuer[] IntializeRescuers(string[] monitoredEntities) { var rescuers = new IRescuer[monitoredEntities.Length]; for (int i = 0; i < rescuers.Length; i++) { if (String.IsNullOrWhiteSpace(monitoredEntities[i])) { var entitiesString = ToFlatString(monitoredEntities); throw new ArgumentException($"monitored entity name can't be null or empty! FailedIndex: {i} Array: [{entitiesString}]"); } rescuers[i] = _factory.Create(); rescuers[i].Connect(monitoredEntities[i]); } return rescuers; } public void DoWork(IRescuer[] rescuers) { for (int i = 0; i < rescuers.Length; i++) { rescuers[i].MonitorAndRescue(); } } private static string ToFlatString(string[] array) { var builder = new StringBuilder(); foreach (var entity in array) { builder.Append(entity); builder.Append(","); } var str = builder.ToString(); return str.Remove(str.Length - 1, 1); } } }```
a1fcbce2-bdf2-4450-b75b-a087c6735a59
{ "language": "C#" }
```c# namespace ReamQuery.Test { using System; using Xunit; using ReamQuery.Helpers; using Microsoft.CodeAnalysis.Text; public class Helpers { [Fact] public void String_InsertTextAt() { var inp = "\r\n text\r\n"; var exp = "\r\n new text\r\n"; var output = inp.InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines_And_InsertTextAt() { var inp = "\r\n text\n"; var exp = "\r\n new text\r\n"; var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " text" + Environment.NewLine; var output = inp.NormalizeNewlines(); Assert.Equal(exp, output); } [Fact] public void String_ReplaceToken() { var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine; var exp = Environment.NewLine + Environment.NewLine + " " + Environment.NewLine; LinePosition pos; var output = inp.ReplaceToken("token", string.Empty, out pos); Assert.Equal(new LinePosition(2, 1), pos); Assert.Equal(exp, output); } } } ``` Fix string test for ubuntu
```c# namespace ReamQuery.Test { using System; using Xunit; using ReamQuery.Helpers; using Microsoft.CodeAnalysis.Text; public class Helpers { [Fact] public void String_InsertTextAt() { var inp = Environment.NewLine + " text" + Environment.NewLine; var exp = Environment.NewLine + " new text" + Environment.NewLine; var output = inp.InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines_And_InsertTextAt() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " new text" + Environment.NewLine; var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " text" + Environment.NewLine; var output = inp.NormalizeNewlines(); Assert.Equal(exp, output); } [Fact] public void String_ReplaceToken() { var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine; var exp = Environment.NewLine + Environment.NewLine + " " + Environment.NewLine; LinePosition pos; var output = inp.ReplaceToken("token", string.Empty, out pos); Assert.Equal(new LinePosition(2, 1), pos); Assert.Equal(exp, output); } } } ```
0c3054a8-0e00-4c25-bfef-f06942f9cd9f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Extensions; using Foundatio.Utility; namespace Foundatio.Messaging { public abstract class MessageBusBase : IMessagePublisher, IDisposable { private readonly CancellationTokenSource _queueDisposedCancellationTokenSource; private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>(); public MessageBusBase() { _queueDisposedCancellationTokenSource = new CancellationTokenSource(); TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100)); } private Task DoMaintenance() { Trace.WriteLine("Doing maintenance..."); foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) { _delayedMessages.Remove(message); Publish(message.MessageType, message.Message); } return TaskHelper.Completed(); } public abstract void Publish(Type messageType, object message, TimeSpan? delay = null); protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) { if (message == null) throw new ArgumentNullException("message"); _delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) }); } protected class DelayedMessage { public DateTime SendTime { get; set; } public Type MessageType { get; set; } public object Message { get; set; } } public virtual void Dispose() { _queueDisposedCancellationTokenSource.Cancel(); } } } ``` Disable delayed messages to see what effect it has on tests.
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Extensions; using Foundatio.Utility; namespace Foundatio.Messaging { public abstract class MessageBusBase : IMessagePublisher, IDisposable { private readonly CancellationTokenSource _queueDisposedCancellationTokenSource; private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>(); public MessageBusBase() { _queueDisposedCancellationTokenSource = new CancellationTokenSource(); //TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100)); } private Task DoMaintenance() { Trace.WriteLine("Doing maintenance..."); foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) { _delayedMessages.Remove(message); Publish(message.MessageType, message.Message); } return TaskHelper.Completed(); } public abstract void Publish(Type messageType, object message, TimeSpan? delay = null); protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) { if (message == null) throw new ArgumentNullException("message"); _delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) }); } protected class DelayedMessage { public DateTime SendTime { get; set; } public Type MessageType { get; set; } public object Message { get; set; } } public virtual void Dispose() { _queueDisposedCancellationTokenSource.Cancel(); } } } ```
bac8191d-da02-45eb-b3a4-bcfc76e48521
{ "language": "C#" }
```c# using System; using Shouldly; using Xunit; namespace Cake.Figlet.Tests { public class FigletTests { [Fact] public void Figlet_can_render() { const string expected = @" _ _ _ _ __ __ _ _ | | | | ___ | || | ___ \ \ / / ___ _ __ | | __| | | |_| | / _ \| || | / _ \ \ \ /\ / / / _ \ | '__|| | / _` | | _ || __/| || || (_) | _ \ V V / | (_) || | | || (_| | |_| |_| \___||_||_| \___/ ( ) \_/\_/ \___/ |_| |_| \__,_| |/ "; FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected); } } public static class ShouldlyAsciiExtensions { /// <summary> /// Helper to allow the expected ASCII art to be on it's own line when declaring /// the expected value in the source code /// </summary> /// <param name="input">The input.</param> /// <param name="expected">The expected.</param> public static void ShouldBeWithLeadingLineBreak(this string input, string expected) { (Environment.NewLine + input).ShouldBe(expected, StringCompareShould.IgnoreLineEndings); } } } ``` Revert "(GH-36) Fix broken test"
```c# using System; using Shouldly; using Xunit; namespace Cake.Figlet.Tests { public class FigletTests { [Fact] public void Figlet_can_render() { const string expected = @" _ _ _ _ __ __ _ _ | | | | ___ | || | ___ \ \ / / ___ _ __ | | __| | | |_| | / _ \| || | / _ \ \ \ /\ / / / _ \ | '__|| | / _` | | _ || __/| || || (_) | _ \ V V / | (_) || | | || (_| | |_| |_| \___||_||_| \___/ ( ) \_/\_/ \___/ |_| |_| \__,_| |/ "; FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected); } } public static class ShouldlyAsciiExtensions { /// <summary> /// Helper to allow the expected ASCII art to be on it's own line when declaring /// the expected value in the source code /// </summary> /// <param name="input">The input.</param> /// <param name="expected">The expected.</param> public static void ShouldBeWithLeadingLineBreak(this string input, string expected) { (Environment.NewLine + input).ShouldBe(expected); } } } ```
4eeeaa87-1ebe-40cf-90b6-9f5ce0c24f11
{ "language": "C#" }
```c# namespace System.Collections.Async { /// <summary> /// This exception is thrown when you call <see cref="AsyncEnumerable{T}.Break"/>. /// </summary> public sealed class ForEachAsyncCanceledException : OperationCanceledException { } } ``` Fix xml comment cref compiler warning
```c# namespace System.Collections.Async { /// <summary> /// This exception is thrown when you call <see cref="ForEachAsyncExtensions.Break"/>. /// </summary> public sealed class ForEachAsyncCanceledException : OperationCanceledException { } } ```
b2655ea8-2d08-4f00-8fc9-5e2786bfdd36
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Text; namespace MotleyFlash.AspNetCore.MessageProviders { public class SessionMessageProvider : IMessageProvider { public SessionMessageProvider(ISession session) { this.session = session; } private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; private readonly ISession session; private const string sessionKey = "motleyflash-session-message-provider"; public object Get() { byte[] value; object messages = null; if (session.TryGetValue(sessionKey, out value)) { if (value != null) { messages = JsonConvert.DeserializeObject( Encoding.UTF8.GetString(value, 0, value.Length), jsonSerializerSettings); } } return messages; } public void Set(object messages) { session.Set( sessionKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject( messages, jsonSerializerSettings))); session.CommitAsync(); } } } ``` Remove session-commit statement that is not needed and already handled by middleware
```c# using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Text; namespace MotleyFlash.AspNetCore.MessageProviders { public class SessionMessageProvider : IMessageProvider { public SessionMessageProvider(ISession session) { this.session = session; } private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; private readonly ISession session; private const string sessionKey = "motleyflash-session-message-provider"; public object Get() { byte[] value; object messages = null; if (session.TryGetValue(sessionKey, out value)) { if (value != null) { messages = JsonConvert.DeserializeObject( Encoding.UTF8.GetString(value, 0, value.Length), jsonSerializerSettings); } } return messages; } public void Set(object messages) { session.Set( sessionKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject( messages, jsonSerializerSettings))); } } } ```
8c3fdc6b-f8bb-4a79-ac89-6d128d514e04
{ "language": "C#" }
```c# using System; using Csla.Server; namespace Csla.Testing.Business.DataPortal { /// <summary> /// Basically this test class exposes protected DataPortal constructor overloads to the /// Unit Testing System, allowing for a more fine-grained Unit Tests /// </summary> public class TestableDataPortal : Csla.Server.DataPortal { public TestableDataPortal() : base(){} public TestableDataPortal(string cslaAuthorizationProviderAppSettingName): base(cslaAuthorizationProviderAppSettingName) { } public TestableDataPortal(Type authProviderType):base(authProviderType) { } public static void Setup() { _authorizer = null; } public Type AuthProviderType { get { return _authorizer.GetType(); } } public IAuthorizeDataPortal AuthProvider { get { return _authorizer; } } public bool NullAuthorizerUsed { get { return AuthProviderType == typeof (NullAuthorizer); } } } }``` Update to use property, not field. bugid: 146
```c# using System; using Csla.Server; namespace Csla.Testing.Business.DataPortal { /// <summary> /// Basically this test class exposes protected DataPortal constructor overloads to the /// Unit Testing System, allowing for a more fine-grained Unit Tests /// </summary> public class TestableDataPortal : Csla.Server.DataPortal { public TestableDataPortal() : base(){} public TestableDataPortal(string cslaAuthorizationProviderAppSettingName): base(cslaAuthorizationProviderAppSettingName) { } public TestableDataPortal(Type authProviderType):base(authProviderType) { } public static void Setup() { Authorizer = null; } public Type AuthProviderType { get { return Authorizer.GetType(); } } public IAuthorizeDataPortal AuthProvider { get { return Authorizer; } } public bool NullAuthorizerUsed { get { return AuthProviderType == typeof (NullAuthorizer); } } } }```
dc4d1d03-0958-4863-bd94-e243b1705189
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using ReactiveUI.Routing.Presentation; using Splat; namespace ReactiveUI.Routing.UWP { public class PagePresenter : Presenter<PagePresenterRequest> { private readonly Frame host; private readonly IViewLocator locator; public PagePresenter(Frame host, IViewLocator locator = null) { this.host = host ?? throw new ArgumentNullException(nameof(host)); this.locator = locator ?? Locator.Current.GetService<IViewLocator>(); } protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request) { return Observable.Create<PresenterResponse>(o => { try { var view = locator.ResolveView(request.ViewModel); view.ViewModel = request.ViewModel; host.Navigate(view.GetType()); o.OnNext(new PresenterResponse(view)); o.OnCompleted(); } catch (Exception ex) { o.OnError(ex); } return new CompositeDisposable(); }); } public static IDisposable RegisterHost(Frame control) { var resolver = Locator.Current.GetService<IMutablePresenterResolver>(); return resolver.Register(new PagePresenter(control)); } } } ``` Make the UWP page presenter us a common content control
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using ReactiveUI.Routing.Presentation; using Splat; namespace ReactiveUI.Routing.UWP { public class PagePresenter : Presenter<PagePresenterRequest> { private readonly ContentControl host; private readonly IViewLocator locator; public PagePresenter(ContentControl host, IViewLocator locator = null) { this.host = host ?? throw new ArgumentNullException(nameof(host)); this.locator = locator ?? Locator.Current.GetService<IViewLocator>(); } protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request) { return Observable.Create<PresenterResponse>(o => { try { var view = locator.ResolveView(request.ViewModel); var disposable = view.WhenActivated(d => { o.OnNext(new PresenterResponse(view)); o.OnCompleted(); }); view.ViewModel = request.ViewModel; host.Content = view; return disposable; } catch (Exception ex) { o.OnError(ex); throw; } }); } public static IDisposable RegisterHost(ContentControl control) { var resolver = Locator.Current.GetService<IMutablePresenterResolver>(); return resolver.Register(new PagePresenter(control)); } } } ```
3b52c880-c5f8-43a0-b152-6f7e6b713384
{ "language": "C#" }
```c# using System; using System.Runtime.InteropServices; using System.Security; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access. /// </summary> public sealed class SecureUsernamePasswordCredentials : Credentials { /// <summary> /// Callback to acquire a credential object. /// </summary> /// <param name="cred">The newly created credential object.</param> /// <returns>0 for success, &lt; 0 to indicate an error, &gt; 0 to indicate no credential was acquired.</returns> protected internal override int GitCredentialHandler(out IntPtr cred) { if (Username == null || Password == null) { throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password."); } IntPtr passwordPtr = IntPtr.Zero; try { passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password); return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr)); } finally { Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); } } /// <summary> /// Username for username/password authentication (as in HTTP basic auth). /// </summary> public string Username { get; set; } /// <summary> /// Password for username/password authentication (as in HTTP basic auth). /// </summary> public SecureString Password { get; set; } } } ``` Fix compile error around exporting SecureString
```c# using System; using System.Runtime.InteropServices; using System.Security; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access. /// </summary> public sealed class SecureUsernamePasswordCredentials : Credentials { /// <summary> /// Callback to acquire a credential object. /// </summary> /// <param name="cred">The newly created credential object.</param> /// <returns>0 for success, &lt; 0 to indicate an error, &gt; 0 to indicate no credential was acquired.</returns> protected internal override int GitCredentialHandler(out IntPtr cred) { if (Username == null || Password == null) { throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password."); } IntPtr passwordPtr = IntPtr.Zero; try { #if NET40 passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password); #else passwordPtr = SecureStringMarshal.SecureStringToCoTaskMemUnicode(Password); #endif return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr)); } finally { #if NET40 Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); #else SecureStringMarshal.ZeroFreeCoTaskMemUnicode(passwordPtr); #endif } } /// <summary> /// Username for username/password authentication (as in HTTP basic auth). /// </summary> public string Username { get; set; } /// <summary> /// Password for username/password authentication (as in HTTP basic auth). /// </summary> public SecureString Password { get; set; } } } ```
e51b9810-3050-4ac2-9301-2b974ae37e14
{ "language": "C#" }
```c# //----------------------------------------------------------------------- // <copyright company="TheNucleus"> // Copyright (c) TheNucleus. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Nuclei.Build; [assembly: AssemblyCulture("")] // Resources [assembly: NeutralResourcesLanguage("en-US")] // 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: AssemblyTrademark("")] // 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)] // Indicate that the assembly is CLS compliant. [assembly: CLSCompliant(true)] // The time the assembly was build [assembly: AssemblyBuildTime(buildTime: "1900-01-01T00:00:00.0000000+00:00")] // The version from which the assembly was build [module: SuppressMessage( "Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Justification = "It's a VCS revision, not a version")] [assembly: AssemblyBuildInformation(buildNumber: 0, versionControlInformation: "1234567890123456789012345678901234567890")] ``` Remove the build attributes because they'll be generated with a full namespace
```c# //----------------------------------------------------------------------- // <copyright company="TheNucleus"> // Copyright (c) TheNucleus. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Nuclei.Build; [assembly: AssemblyCulture("")] // Resources [assembly: NeutralResourcesLanguage("en-US")] // 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: AssemblyTrademark("")] // 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)] // Indicate that the assembly is CLS compliant. [assembly: CLSCompliant(true)] ```
20292be3-72c8-4784-8ace-51f097d54c76
{ "language": "C#" }
```c# using System; using System.Text.RegularExpressions; namespace Floobits.Common { public class Constants { static public string baseDir = FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "floobits"); static public string shareDir = FilenameUtils.concat(baseDir, "share"); static public string version = "0.11"; static public string pluginVersion = "0.01"; static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com"; static public int OUTBOUND_FILTER_PROXY_PORT = 443; static public string floobitsDomain = "floobits.com"; static public string defaultHost = "floobits.com"; static public int defaultPort = 3448; static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled); static public int TOO_MANY_BIG_DIRS = 50; } } ``` Use the same folder as the JAVA implementation
```c# using System; using System.Text.RegularExpressions; namespace Floobits.Common { public class Constants { static public string baseDir = baseDirInit(); static public string shareDir = FilenameUtils.concat(baseDir, "share"); static public string version = "0.11"; static public string pluginVersion = "0.01"; static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com"; static public int OUTBOUND_FILTER_PROXY_PORT = 443; static public string floobitsDomain = "floobits.com"; static public string defaultHost = "floobits.com"; static public int defaultPort = 3448; static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled); static public int TOO_MANY_BIG_DIRS = 50; static public string baseDirInit() { return FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "floobits"); } } } ```
234a4150-186f-4a1c-ba7b-591bedf13577
{ "language": "C#" }
```c# using System; using BmpListener.Bmp; using BmpListener.JSON; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace BmpListener.ConsoleExample { internal class Program { private static void Main() { JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new StringEnumConverter()); return settings; }; var bmpListener = new BmpListener(); bmpListener.Start(WriteJson).Wait(); } private static void WriteJson(BmpMessage msg) { var json = JsonConvert.SerializeObject(msg); Console.WriteLine(json); } } }``` Change default JSON serialization to CamelCase
```c# using System; using BmpListener.Bmp; using BmpListener.JSON; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace BmpListener.ConsoleExample { internal class Program { private static void Main() { JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new StringEnumConverter()); settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); return settings; }; var bmpListener = new BmpListener(); bmpListener.Start(WriteJson).Wait(); } private static void WriteJson(BmpMessage msg) { var json = JsonConvert.SerializeObject(msg); Console.WriteLine(json); } } }```
7f126d35-2817-4f2c-9d87-46912eeab990
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataGenerator { class Program { static void Main(string[] args) { var gen = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]); for (int i = 0; i < 25; i++) { Console.WriteLine(gen.Generate()); } Console.ReadLine(); } } } ``` Use Timer based Observable to generate data
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; namespace DataGenerator { class Program { static void Main(string[] args) { var data = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]); var tick = TimeSpan.Parse(ConfigurationSettings.AppSettings["timespan"]); Observable .Timer(TimeSpan.Zero, tick) .Subscribe( t => { Console.WriteLine(data.Generate()); } ); Console.ReadLine(); } } } ```
fcc4aeee-0336-4d49-923a-8650c1a7d0a7
{ "language": "C#" }
```c# using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } } ``` Update server side API for single multiple answer question
```c# using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } } ```
7df2fd2d-7532-4361-82e4-546bb98edf51
{ "language": "C#" }
```c# namespace Mappy.Models { using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using Mappy.Data; using Mappy.Database; public interface IMapViewSettingsModel { IObservable<bool> GridVisible { get; } IObservable<Color> GridColor { get; } IObservable<Size> GridSize { get; } IObservable<bool> HeightmapVisible { get; } IObservable<bool> FeaturesVisible { get; } IObservable<IFeatureDatabase> FeatureRecords { get; } IObservable<IMainModel> Map { get; } IObservable<int> ViewportWidth { get; set; } IObservable<int> ViewportHeight { get; set; } void SetViewportSize(Size size); void SetViewportLocation(Point pos); void OpenFromDragDrop(string filename); void DragDropData(IDataObject data, Point loc); } } ``` Remove setters from IObservable properties
```c# namespace Mappy.Models { using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using Mappy.Data; using Mappy.Database; public interface IMapViewSettingsModel { IObservable<bool> GridVisible { get; } IObservable<Color> GridColor { get; } IObservable<Size> GridSize { get; } IObservable<bool> HeightmapVisible { get; } IObservable<bool> FeaturesVisible { get; } IObservable<IFeatureDatabase> FeatureRecords { get; } IObservable<IMainModel> Map { get; } IObservable<int> ViewportWidth { get; } IObservable<int> ViewportHeight { get; } void SetViewportSize(Size size); void SetViewportLocation(Point pos); void OpenFromDragDrop(string filename); void DragDropData(IDataObject data, Point loc); } } ```
68e8464f-2fe0-4d6b-a171-51792cf66a6f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpeningsMoeWpfClient { class FfmpegMovieConverter : IMovieConverter { private string ffmpegPath; public Task<string> ConvertMovie(string sourcePath, string targetPath) { var tcs = new TaskCompletionSource<string>(); var process = new Process { StartInfo = { UseShellExecute = false, FileName = ffmpegPath, Arguments = $@"-i ""{sourcePath}"" -vcodec msmpeg4v2 -acodec libmp3lame -strict -2 ""{targetPath}""", CreateNoWindow = true }, EnableRaisingEvents = true }; process.Exited += (sender, args) => { if(process.ExitCode == 0) tcs.SetResult(targetPath); else tcs.SetException(new InvalidOperationException("SOMETHING WENT WRONG")); process.Dispose(); }; process.Start(); process.PriorityClass = ProcessPriorityClass.BelowNormal; return tcs.Task; } public FfmpegMovieConverter(string ffmpegPath) { this.ffmpegPath = ffmpegPath; } } } ``` Split responsibility of ConvertMovie() method
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpeningsMoeWpfClient { class FfmpegMovieConverter : IMovieConverter { private string ffmpegPath; private Task<int> LaunchProcess(Func<Process> factory, Action<Process> postLaunchConfiguration) { var tcs = new TaskCompletionSource<int>(); var process = factory(); process.Exited += (sender, args) => { tcs.SetResult(process.ExitCode); process.Dispose(); }; process.Start(); postLaunchConfiguration(process); return tcs.Task; } public async Task<string> ConvertMovie(string sourcePath, string targetPath) { int exitCode = await LaunchProcess(() => new Process { StartInfo = { UseShellExecute = false, FileName = ffmpegPath, Arguments = $@"-i ""{sourcePath}"" -vcodec msmpeg4v2 -acodec libmp3lame -strict -2 ""{targetPath}""", CreateNoWindow = true }, EnableRaisingEvents = true }, process => { process.PriorityClass = ProcessPriorityClass.BelowNormal; }); if(exitCode == 0) return targetPath; throw new InvalidOperationException("SOMETHING WENT WRONG"); } public FfmpegMovieConverter(string ffmpegPath) { this.ffmpegPath = ffmpegPath; } } } ```
3422a63d-d481-41f8-82e4-ab48ed644e8b
{ "language": "C#" }
```c# using System.Linq; using JetBrains.Annotations; using JetBrains.ReSharper.Feature.Services.Lookup; using JetBrains.ReSharper.PostfixTemplates.LookupItems; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace JetBrains.ReSharper.PostfixTemplates.Templates { // todo: (Bar) foo.par - available in auto? [PostfixTemplate( templateName: "par", description: "Parenthesizes current expression", example: "(expr)")] public class ParenthesizedExpressionTemplate : IPostfixTemplate { public ILookupItem CreateItem(PostfixTemplateContext context) { if (context.IsAutoCompletion) return null; PrefixExpressionContext bestContext = null; foreach (var expressionContext in context.Expressions.Reverse()) { if (CommonUtils.IsNiceExpression(expressionContext.Expression)) { bestContext = expressionContext; break; } } return new ParenthesesItem(bestContext ?? context.OuterExpression); } private sealed class ParenthesesItem : ExpressionPostfixLookupItem<ICSharpExpression> { public ParenthesesItem([NotNull] PrefixExpressionContext context) : base("par", context) { } protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression) { return factory.CreateExpression("($0)", expression); } } } }``` Allow .par in auto in case of '(T) expr.par'
```c# using System.Linq; using JetBrains.Annotations; using JetBrains.ReSharper.Feature.Services.Lookup; using JetBrains.ReSharper.PostfixTemplates.LookupItems; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace JetBrains.ReSharper.PostfixTemplates.Templates { [PostfixTemplate( templateName: "par", description: "Parenthesizes current expression", example: "(expr)")] public class ParenthesizedExpressionTemplate : IPostfixTemplate { public ILookupItem CreateItem(PostfixTemplateContext context) { PrefixExpressionContext bestContext = null; foreach (var expressionContext in context.Expressions.Reverse()) { if (CommonUtils.IsNiceExpression(expressionContext.Expression)) { bestContext = expressionContext; break; } } // available in auto over cast expressions var targetContext = bestContext ?? context.OuterExpression; var insideCastExpression = CastExpressionNavigator.GetByOp(targetContext.Expression) != null; if (!insideCastExpression && context.IsAutoCompletion) return null; return new ParenthesesItem(targetContext); } private sealed class ParenthesesItem : ExpressionPostfixLookupItem<ICSharpExpression> { public ParenthesesItem([NotNull] PrefixExpressionContext context) : base("par", context) { } protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression) { return factory.CreateExpression("($0)", expression); } } } }```
69bc573f-eb4c-4589-83c0-28d30dba7e63
{ "language": "C#" }
```c# @using So.ImageResizer.Helpers @{ Style.Include("slimbox2.css"); Script.Require("jQuery").AtFoot(); Script.Include("slimbox2.js").AtFoot(); } @if (!string.IsNullOrEmpty(Model.ContentField.FileNames)) { <div class="stripGallery"> @foreach (var fileName in Model.ContentField.FileNames.Split(';')) { <a href="@fileName" rel="lightbox-gallery"> @{ var alternateText = string.IsNullOrEmpty(Model.ContentField.AlternateText) ? Path.GetFileNameWithoutExtension(fileName) : Model.ContentField.AlternateText; } <img width="100" height="80" src='@string.Format("/resizedImage?url={0}&width=100&height=80&maxWidth=100&maxheight=80&cropMode={1}&scale={2}&stretchMode={3}", fileName, ResizeSettingType.CropMode.Auto, ResizeSettingType.ScaleMode.DownscaleOnly, ResizeSettingType.StretchMode.Proportionally)' alt="@alternateText"/> </a> } </div> }``` Fix AgileUploader (remove SO image resizer)
```c# @{ Style.Include("slimbox2.css"); Script.Require("jQuery").AtFoot(); Script.Include("slimbox2.js").AtFoot(); } @if (!string.IsNullOrEmpty(Model.ContentField.FileNames)) { <div class="stripGallery"> @foreach (var fileName in Model.ContentField.FileNames.Split(';')) { <a href="@fileName" rel="lightbox-gallery"> @{ var alternateText = string.IsNullOrEmpty(Model.ContentField.AlternateText) ? Path.GetFileNameWithoutExtension(fileName) : Model.ContentField.AlternateText; } <img alt="@alternateText" src='@Display.ResizeMediaUrl(Width: 250, Path: fileName)' /> </a> } </div> }```
cd6a7be0-1661-48f7-9db4-aa35a37ab717
{ "language": "C#" }
```c# using System; namespace CmnTools.Suice { /// <summary> /// @author DisTurBinG /// </summary> public class SingletonProvider : AbstractProvider { internal object Instance; public SingletonProvider (Type providedType) : base(providedType) { } internal virtual void CreateSingletonInstance() { SetInstance(Activator.CreateInstance(ProvidedType, ConstructorDependencies)); } internal void SetInstance (object instance) { DependencyProxy dependencyProxy = Instance as DependencyProxy; if (dependencyProxy == null) { Instance = instance; } else { dependencyProxy.SetInstance(instance); } } protected override object ProvideObject() { return Instance ?? (Instance = new DependencyProxy (ProvidedType)); } } } ``` Fix for Binding singleton to instance.
```c# using System; namespace CmnTools.Suice { /// <summary> /// @author DisTurBinG /// </summary> public class SingletonProvider : AbstractProvider { internal object Instance; public SingletonProvider (Type providedType) : base(providedType) { } internal virtual void CreateSingletonInstance() { if (Instance == null) { SetInstance(Activator.CreateInstance(ProvidedType, ConstructorDependencies)); } } internal void SetInstance (object instance) { DependencyProxy dependencyProxy = Instance as DependencyProxy; if (dependencyProxy == null) { Instance = instance; } else { dependencyProxy.SetInstance(instance); } } protected override object ProvideObject() { return Instance ?? (Instance = new DependencyProxy (ProvidedType)); } } } ```
a40ea33e-7a81-4ea3-b7aa-791c9bd78063
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Xml.Linq; namespace Twilio.TwiML.Mvc { public class TwiMLResult : ActionResult { XDocument data; public TwiMLResult() { } public TwiMLResult(string twiml) { data = XDocument.Parse(twiml); } public TwiMLResult(XDocument twiml) { data = twiml; } public TwiMLResult(TwilioResponse response) { data = response.ToXDocument(); } public override void ExecuteResult(ControllerContext controllerContext) { var context = controllerContext.RequestContext.HttpContext; context.Response.ContentType = "application/xml"; if (data == null) { data = new XDocument(new XElement("Response")); } data.Save(context.Response.Output); } } } ``` Fix NullReference when using T4MVC
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Xml.Linq; namespace Twilio.TwiML.Mvc { public class TwiMLResult : ActionResult { XDocument data; public TwiMLResult() { } public TwiMLResult(string twiml) { data = XDocument.Parse(twiml); } public TwiMLResult(XDocument twiml) { data = twiml; } public TwiMLResult(TwilioResponse response) { if (response != null) data = response.ToXDocument(); } public override void ExecuteResult(ControllerContext controllerContext) { var context = controllerContext.RequestContext.HttpContext; context.Response.ContentType = "application/xml"; if (data == null) { data = new XDocument(new XElement("Response")); } data.Save(context.Response.Output); } } } ```
9912a9d7-0cc1-4f0b-83bc-f6a3cc111b57
{ "language": "C#" }
```c# using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // URL is MAX 19 Chars. int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength; } totalCount += input.Length - prevIndex; return totalCount; } } } ``` Fix a bug of wrong counting characters with HTTPS URL
```c# using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // URL is MAX 20 Chars (if URL has HTTPS scheme, URL is MAX 21 Chars) int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; bool isHasHttpsScheme = m.Groups[0].Value.Contains("https"); if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0)) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0); } totalCount += input.Length - prevIndex; return totalCount; } } } ```
8da94085-ed7a-45a0-89a6-88f23f3d5f7b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using ExcelDna.Integration; namespace RtdArrayTest { public static class TestFunctions { public static object RtdArrayTest(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } } } ``` Add problem function (with IsMacroType=true)
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using ExcelDna.Integration; namespace RtdArrayTest { public static class TestFunctions { public static object RtdArrayTest(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } // NOTE: This is that problem case discussed in https://groups.google.com/d/topic/exceldna/62cgmRMVtfQ/discussion // It seems that the DisconnectData will not be called on updates triggered by parameters from the sheet // for RTD functions that are marked IsMacroType=true. [ExcelFunction(IsMacroType=true)] public static object RtdArrayTestMT(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, "X" + prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } } } ```
04755a07-b0ee-4dfd-870d-f75f73d741c5
{ "language": "C#" }
```c# // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using System.Collections; public class PortraitFlipTest : MonoBehaviour { void Update () { Transform t = gameObject.transform.FindChild("Canvas/JohnCharacter"); if (t == null) { return; } if (t.transform.localScale.x != -1f) { IntegrationTest.Fail("Character object not flipped horizontally"); } } } ``` Use transform.Find instead of deprecated transform.FindChild
```c# // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using System.Collections; public class PortraitFlipTest : MonoBehaviour { void Update () { Transform t = gameObject.transform.Find("Canvas/JohnCharacter"); if (t == null) { return; } if (t.transform.localScale.x != -1f) { IntegrationTest.Fail("Character object not flipped horizontally"); } } } ```
80a0894c-bfd0-4c10-b134-8604d1bab0ad
{ "language": "C#" }
```c# using NUnit.Framework; namespace FullSerializer.Tests.InitialInstance { public class SimpleModel { public int A; } public class InitialInstanceTests { [Test] public void TestInitialInstance() { SimpleModel model1 = new SimpleModel { A = 3 }; fsData data; var serializer = new fsSerializer(); Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded); model1.A = 1; SimpleModel model2 = model1; Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded); Assert.AreEqual(model1.A, 3); Assert.AreEqual(model2.A, 3); Assert.IsTrue(ReferenceEquals(model1, model2)); } } }``` Add test description and fix param order in Assert call
```c# using NUnit.Framework; namespace FullSerializer.Tests.InitialInstance { public class SimpleModel { public int A; } public class InitialInstanceTests { [Test] public void TestPopulateObject() { // This test verifies that when we pass in an existing object // instance that same instance is used to deserialize into, ie, // we can do the equivalent of Json.NET's PopulateObject SimpleModel model1 = new SimpleModel { A = 3 }; fsData data; var serializer = new fsSerializer(); Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded); model1.A = 1; SimpleModel model2 = model1; Assert.AreEqual(1, model1.A); Assert.AreEqual(1, model2.A); Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded); Assert.AreEqual(3, model1.A); Assert.AreEqual(3, model2.A); Assert.IsTrue(ReferenceEquals(model1, model2)); } } }```
4e1d8109-88b1-4936-a013-9cf1647dfa1e
{ "language": "C#" }
```c# using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zermelo.API")] [assembly: AssemblyDescription("Connect to Zermelo from your .NET app")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zermelo.API")] [assembly: AssemblyCopyright("Copyright 2016 Arthur Rump")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Make internal classes and functions available for testing [assembly: InternalsVisibleTo("Zermelo.API.Tests")] ``` Change assembly version from 2.0.0.0 to 2.0.*
```c# using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zermelo.API")] [assembly: AssemblyDescription("Connect to Zermelo from your .NET app")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zermelo.API")] [assembly: AssemblyCopyright("Copyright 2016 Arthur Rump")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] // Make internal classes and functions available for testing [assembly: InternalsVisibleTo("Zermelo.API.Tests")] ```
91ca70f9-ec19-4349-825f-95f0e65b4173
{ "language": "C#" }
```c# using System.Collections.Generic; using System.IO; namespace JiebaNet.Analyser { public abstract class KeywordExtractor { protected static readonly List<string> DefaultStopWords = new List<string>() { "the", "of", "is", "and", "to", "in", "that", "we", "for", "an", "are", "by", "be", "as", "on", "with", "can", "if", "from", "which", "you", "it", "this", "then", "at", "have", "all", "not", "one", "has", "or", "that" }; protected virtual ISet<string> StopWords { get; set; } public void SetStopWords(string stopWordsFile) { var path = Path.GetFullPath(stopWordsFile); if (File.Exists(path)) { var lines = File.ReadAllLines(path); StopWords = new HashSet<string>(); foreach (var line in lines) { StopWords.Add(line.Trim()); } } } public abstract IEnumerable<string> ExtractTags(string text, int count = 20, IEnumerable<string> allowPos = null); public abstract IEnumerable<WordWeightPair> ExtractTagsWithWeight(string text, int count = 20, IEnumerable<string> allowPos = null); } }``` Use empty stopwords set when the default stopwords file is missing.
```c# using System.Collections.Generic; using System.IO; namespace JiebaNet.Analyser { public abstract class KeywordExtractor { protected static readonly List<string> DefaultStopWords = new List<string>() { "the", "of", "is", "and", "to", "in", "that", "we", "for", "an", "are", "by", "be", "as", "on", "with", "can", "if", "from", "which", "you", "it", "this", "then", "at", "have", "all", "not", "one", "has", "or", "that" }; protected virtual ISet<string> StopWords { get; set; } public void SetStopWords(string stopWordsFile) { StopWords = new HashSet<string>(); var path = Path.GetFullPath(stopWordsFile); if (File.Exists(path)) { var lines = File.ReadAllLines(path); foreach (var line in lines) { StopWords.Add(line.Trim()); } } } public abstract IEnumerable<string> ExtractTags(string text, int count = 20, IEnumerable<string> allowPos = null); public abstract IEnumerable<WordWeightPair> ExtractTagsWithWeight(string text, int count = 20, IEnumerable<string> allowPos = null); } }```
81d61289-d81a-489d-82dd-cb1a05d8f41b
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion(SolutionInfo.Version + ".0")] [assembly: AssemblyInformationalVersion(SolutionInfo.Version)] [assembly: AssemblyFileVersion(SolutionInfo.Version + ".0")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub")] [assembly: AssemblyProduct("Octokit")] [assembly: AssemblyCopyright("Copyright GitHub 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Octokit.Tests")] [assembly: InternalsVisibleTo("OctokitRT.Tests")] [assembly: CLSCompliant(false)] class SolutionInfo { public const string Version = "0.1.0"; } ``` Fix up InternalsVisibleTo to new name
```c# using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion(SolutionInfo.Version + ".0")] [assembly: AssemblyInformationalVersion(SolutionInfo.Version)] [assembly: AssemblyFileVersion(SolutionInfo.Version + ".0")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub")] [assembly: AssemblyProduct("Octokit")] [assembly: AssemblyCopyright("Copyright GitHub 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Octokit.Tests")] [assembly: InternalsVisibleTo("Octokit.Tests-NetCore45")] [assembly: CLSCompliant(false)] class SolutionInfo { public const string Version = "0.1.0"; } ```
89929b71-4ced-4870-902e-a71bb9abbebf
{ "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; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using XNAControls; namespace EndlessClient.UIControls { public class PictureBox : XNAControl { protected Texture2D _displayPicture; public Optional<Rectangle> SourceRectangle { get; set; } public PictureBox(Texture2D displayPicture, XNAControl parent = null) : base(null, null, parent) { SetNewPicture(displayPicture); if (parent == null) Game.Components.Add(this); SourceRectangle = new Optional<Rectangle>(); } public void SetNewPicture(Texture2D displayPicture) { _displayPicture = displayPicture; _setSize(displayPicture.Width, displayPicture.Height); } public override void Draw(GameTime gameTime) { SpriteBatch.Begin(); SpriteBatch.Draw( _displayPicture, DrawAreaWithOffset, SourceRectangle.HasValue ? SourceRectangle : null, Color.White); SpriteBatch.End(); base.Draw(gameTime); } } } ``` Make SourceRectangle nullable so it doesn't crash.
```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; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using XNAControls; namespace EndlessClient.UIControls { public class PictureBox : XNAControl { protected Texture2D _displayPicture; public Optional<Rectangle?> SourceRectangle { get; set; } public PictureBox(Texture2D displayPicture, XNAControl parent = null) : base(null, null, parent) { SetNewPicture(displayPicture); if (parent == null) Game.Components.Add(this); SourceRectangle = new Optional<Rectangle?>(); } public void SetNewPicture(Texture2D displayPicture) { _displayPicture = displayPicture; _setSize(displayPicture.Width, displayPicture.Height); } public override void Draw(GameTime gameTime) { SpriteBatch.Begin(); SpriteBatch.Draw( _displayPicture, DrawAreaWithOffset, SourceRectangle.HasValue ? SourceRectangle.Value : null, Color.White); SpriteBatch.End(); base.Draw(gameTime); } } } ```
2752ec3a-9f88-43a9-85c1-9b9e8d5f5045
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } } ``` Make foreign key converter thread-safe.
```c# using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); lock (Model.SyncRoot) { var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } } ```
8bc362d9-bb17-4c47-a224-3879be7014c8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Newtonsoft.Json; using OutlookMatters.Core.Http; using OutlookMatters.Core.Mattermost.v4.Interface; namespace OutlookMatters.Core.Mattermost.v4 { public class RestService : IRestService { private readonly IHttpClient _httpClient; public RestService(IHttpClient httpClient) { _httpClient = httpClient; } public void Login(Uri baseUri, Login login, out string token) { var loginUrl = new Uri(baseUri, "api/v4/users/login"); using (var response = _httpClient.Request(loginUrl) .WithContentType("text/json") .Post(JsonConvert.SerializeObject(login))) { token = response.GetHeaderValue("Token"); } } public IEnumerable<Team> GetTeams(Uri baseUri, string token) { throw new NotImplementedException(); } } } ``` Implement rest call to get teams.
```c# using System; using System.Collections.Generic; using Newtonsoft.Json; using OutlookMatters.Core.Http; using OutlookMatters.Core.Mattermost.v4.Interface; namespace OutlookMatters.Core.Mattermost.v4 { public class RestService : IRestService { private readonly IHttpClient _httpClient; public RestService(IHttpClient httpClient) { _httpClient = httpClient; } public void Login(Uri baseUri, Login login, out string token) { var loginUrl = new Uri(baseUri, "api/v4/users/login"); using (var response = _httpClient.Request(loginUrl) .WithContentType("application/json") .Post(JsonConvert.SerializeObject(login))) { token = response.GetHeaderValue("Token"); } } public IEnumerable<Team> GetTeams(Uri baseUri, string token) { var teamsUrl = new Uri(baseUri, "api/v4/teams"); using (var response = _httpClient.Request(teamsUrl) .WithHeader("Authorization", "Bearer " + token) .Get()) { var payload = response.GetPayload(); return JsonConvert.DeserializeObject<IEnumerable<Team>>(payload); } } } }```
fdea2711-92b5-46d5-9caf-f5894f36e247
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Demo.Endpoints; using Distributor; namespace Demo { internal class Program { private static void Main(string[] args) { var distributables = new List<DistributableFile> { new DistributableFile { Id = Guid.NewGuid(), ProfileName = "TestProfile", Name = "test.pdf", Contents = null } }; //Configure the distributor var distributor = new Distributor<DistributableFile>(); distributor.EndpointDeliveryServices.Add(new SharepointDeliveryService()); distributor.EndpointDeliveryServices.Add(new FileSystemDeliveryService()); //Run the Distributor distributor.Distribute(distributables); Console.ReadLine(); } } } ``` Fix import error in demo.
```c# using System; using System.Collections.Generic; using Demo.Endpoints.FileSystem; using Demo.Endpoints.Sharepoint; using Distributor; namespace Demo { internal class Program { private static void Main(string[] args) { var distributables = new List<DistributableFile> { new DistributableFile { Id = Guid.NewGuid(), ProfileName = "TestProfile", Name = "test.pdf", Contents = null } }; //Configure the distributor var distributor = new Distributor<DistributableFile>(); distributor.EndpointDeliveryServices.Add(new SharepointDeliveryService()); distributor.EndpointDeliveryServices.Add(new FileSystemDeliveryService()); //Run the Distributor distributor.Distribute(distributables); Console.ReadLine(); } } } ```
8efe15d0-f16f-4d70-97ea-74e5d36d6a4d
{ "language": "C#" }
```c# using UnityEngine; using UnityEngine.EventSystems; using System.Collections; public class UserInput : MonoBehaviour, IPointerClickHandler { // void Start(){} // void Update(){} // Mutually exclusive for now, priority is in the following order: // Left click for human, // Right for zombie, // Middle for corpse public void OnPointerClick(PointerEventData e) { if(e.button == PointerEventData.InputButton.Left) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.HUMAN, Camera.main.ScreenToWorldPoint(e.position)); } else if(e.button == PointerEventData.InputButton.Right) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.ZOMBIE, Camera.main.ScreenToWorldPoint(e.position)); } else if(e.button == PointerEventData.InputButton.Middle) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.CORPSE, Camera.main.ScreenToWorldPoint(e.position)); } } } ``` Swap human/zombie spawn input so you can spawn zombies on touch screens
```c# using UnityEngine; using UnityEngine.EventSystems; using System.Collections; public class UserInput : MonoBehaviour, IPointerClickHandler { // void Start(){} // void Update(){} // Mutually exclusive for now, priority is in the following order: // Left click for human, // Right for zombie, // Middle for corpse public void OnPointerClick(PointerEventData e) { if(e.button == PointerEventData.InputButton.Left) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.ZOMBIE, Camera.main.ScreenToWorldPoint(e.position)); } else if(e.button == PointerEventData.InputButton.Right) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.HUMAN, Camera.main.ScreenToWorldPoint(e.position)); } else if(e.button == PointerEventData.InputButton.Middle) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.CORPSE, Camera.main.ScreenToWorldPoint(e.position)); } } } ```
def68408-4478-48f0-8744-81b2201fa65b
{ "language": "C#" }
```c# namespace Mappy.UI.Drawables { using System; using System.Drawing; public class DrawableBandbox : IDrawable, IDisposable { private readonly Brush fillBrush; private readonly Pen borderPen; public DrawableBandbox(Brush fillBrush, Pen borderPen, Size size) { this.fillBrush = fillBrush; this.borderPen = borderPen; this.Size = size; } public Size Size { get; private set; } public int Width { get { return this.Size.Width; } } public int Height { get { return this.Size.Height; } } public static DrawableBandbox CreateSimple( Size size, Color color, Color borderColor, int borderWidth = 1) { return new DrawableBandbox( new SolidBrush(color), new Pen(borderColor, borderWidth), size); } public void Draw(Graphics graphics, Rectangle clipRectangle) { graphics.FillRectangle(this.fillBrush, 0, 0, this.Width - 1, this.Height - 1); graphics.DrawRectangle(this.borderPen, 0, 0, this.Width - 1, this.Height - 1); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.fillBrush.Dispose(); this.borderPen.Dispose(); } } } } ``` Replace default parameter with overload
```c# namespace Mappy.UI.Drawables { using System; using System.Drawing; public class DrawableBandbox : IDrawable, IDisposable { private readonly Brush fillBrush; private readonly Pen borderPen; public DrawableBandbox(Brush fillBrush, Pen borderPen, Size size) { this.fillBrush = fillBrush; this.borderPen = borderPen; this.Size = size; } public Size Size { get; private set; } public int Width { get { return this.Size.Width; } } public int Height { get { return this.Size.Height; } } public static DrawableBandbox CreateSimple(Size size, Color color, Color borderColor) { return CreateSimple(size, color, borderColor, 1); } public static DrawableBandbox CreateSimple( Size size, Color color, Color borderColor, int borderWidth) { return new DrawableBandbox( new SolidBrush(color), new Pen(borderColor, borderWidth), size); } public void Draw(Graphics graphics, Rectangle clipRectangle) { graphics.FillRectangle(this.fillBrush, 0, 0, this.Width - 1, this.Height - 1); graphics.DrawRectangle(this.borderPen, 0, 0, this.Width - 1, this.Height - 1); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.fillBrush.Dispose(); this.borderPen.Dispose(); } } } } ```
057f83f5-c866-4785-a80c-deeb7cc86502
{ "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("MonJobs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonJobs")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("763b7fef-ff24-407d-8dce-5313e6129941")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.8.0.0")]``` Increase version to 1.9 to reflect the new AdhocQuery capability change.
```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("MonJobs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonJobs")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("763b7fef-ff24-407d-8dce-5313e6129941")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.9.0.0")]```
3091f241-b219-4f6c-ab60-b6885b02bb8c
{ "language": "C#" }
```c# namespace McIP { using System; using System.Diagnostics; using System.IO; public static class Program { public static void Main() { var si = new ProcessStartInfo("ipconfig", "/all") { RedirectStandardOutput = true, UseShellExecute = false }; var p = Process.Start(si); StreamReader reader = p.StandardOutput; string heading = string.Empty; string line; while ((line = reader.ReadLine()) != null) { if (!string.IsNullOrEmpty(line) && !line.StartsWith(" ", StringComparison.Ordinal)) { heading = line; } if (line.Contains("IP Address")) { Console.WriteLine(heading); Console.WriteLine(line); Console.WriteLine(); } } } } } ``` Handle IPv4 Address and IPv6 Address
```c# namespace McIP { using System; using System.Diagnostics; using System.IO; public static class Program { public static void Main() { var si = new ProcessStartInfo("ipconfig", "/all") { RedirectStandardOutput = true, UseShellExecute = false }; var p = Process.Start(si); StreamReader reader = p.StandardOutput; string heading = string.Empty; bool headingPrinted = false; string line; while ((line = reader.ReadLine()) != null) { if (!string.IsNullOrEmpty(line) && !line.StartsWith(" ", StringComparison.Ordinal)) { heading = line; headingPrinted = false; } if (line.ContainsAny("IP Address", "IPv4 Address", "IPv6 Address")) { if (!headingPrinted) { Console.WriteLine(); Console.WriteLine(heading); headingPrinted = true; } Console.WriteLine(line); } } } private static bool ContainsAny(this string target, params string[] values) { if (values == null) { throw new ArgumentNullException("values"); } foreach (var value in values) { if (target.Contains(value)) { return true; } } return false; } } } ```
e389d11a-5e20-47bf-aac7-aeb77aa465fe
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.ApplicationClasses; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleQuestion"></param> /// <returns></returns> [Route("singlemultiplequestion")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion([FromBody]SingleMultipleQuestion singleMultipleQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleQuestion.singleMultipleAnswerQuestion,singleMultipleQuestion.singleMultipleAnswerQuestionOption); return Ok(singleMultipleQuestion); } } } ``` Create server side API for single multiple answer question
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.ApplicationClasses; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleQuestion"></param> /// <returns></returns> [Route("singlemultiplequestion")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion([FromBody]SingleMultipleQuestion singleMultipleQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleQuestion.singleMultipleAnswerQuestion,singleMultipleQuestion.singleMultipleAnswerQuestionOption); return Ok(singleMultipleQuestion); } } } ```
caaf154d-8ac4-49dc-b30f-384c8f375b73
{ "language": "C#" }
```c# // Copyright 2019 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.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { public class TeamCityScheduledTrigger : TeamCityTrigger { public string BranchFilter { get; set; } public string TriggerRules { get; set; } public bool TriggerBuildAlways { get; set; } //TODO: check public bool WithPendingChangesOnly { get; set; } public bool EnableQueueOptimization { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock("schedule")) { using (writer.WriteBlock("schedulingPolicy = daily")) { writer.WriteLine("hour = 3"); writer.WriteLine("timezone = \"Europe/Berlin\""); } writer.WriteLine($"branchFilter = {BranchFilter.DoubleQuote()}"); writer.WriteLine($"triggerRules = {TriggerRules.DoubleQuote()}"); writer.WriteLine("triggerBuild = always()"); writer.WriteLine("withPendingChangesOnly = false"); writer.WriteLine($"enableQueueOptimization = {EnableQueueOptimization.ToString().ToLowerInvariant()}"); writer.WriteLine("param(\"cronExpression_min\", \"3\")"); } } } } ``` Remove timezone specification for scheduled triggers to use server timezone
```c# // Copyright 2019 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.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { public class TeamCityScheduledTrigger : TeamCityTrigger { public string BranchFilter { get; set; } public string TriggerRules { get; set; } public bool TriggerBuildAlways { get; set; } //TODO: check public bool WithPendingChangesOnly { get; set; } public bool EnableQueueOptimization { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock("schedule")) { using (writer.WriteBlock("schedulingPolicy = daily")) { writer.WriteLine("hour = 3"); } writer.WriteLine($"branchFilter = {BranchFilter.DoubleQuote()}"); writer.WriteLine($"triggerRules = {TriggerRules.DoubleQuote()}"); writer.WriteLine("triggerBuild = always()"); writer.WriteLine("withPendingChangesOnly = false"); writer.WriteLine($"enableQueueOptimization = {EnableQueueOptimization.ToString().ToLowerInvariant()}"); writer.WriteLine("param(\"cronExpression_min\", \"3\")"); } } } } ```
9af3f0e7-675f-4c98-b863-956364e06fe9
{ "language": "C#" }
```c# namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public char Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(Stream f, ref GafFrameData e) { BinaryReader b = new BinaryReader(f); e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadChar(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } } ``` Change char to byte in gaf frame header
```c# namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(Stream f, ref GafFrameData e) { BinaryReader b = new BinaryReader(f); e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } } ```
4aa0341d-ec40-4df7-b18a-7275557a7d54
{ "language": "C#" }
```c# using System.Collections.Generic; namespace Palaso.Extensions { public static class StringExtensions { public static List<string> SplitTrimmed(this string s, char seperator) { var x = s.Split(seperator); var r = new List<string>(); foreach (var part in x) { r.Add(part.Trim()); } return r; } } }``` Make SplitTrimmed give empty list when given white-space-only string
```c# using System.Collections.Generic; namespace Palaso.Extensions { public static class StringExtensions { public static List<string> SplitTrimmed(this string s, char seperator) { if(s.Trim() == string.Empty) return new List<string>(); var x = s.Split(seperator); var r = new List<string>(); foreach (var part in x) { r.Add(part.Trim()); } return r; } } }```
bd7d727a-d5fd-4b5c-a241-2da0bb544d29
{ "language": "C#" }
```c# namespace Snittlistan.Test { using System.IO; using System.Text; using Models; using Raven.Imports.Newtonsoft.Json; using Xunit; public class SerializationTest : DbTest { [Fact] public void CanSerialize8x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create8x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match8x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.AwayTeam); } [Fact] public void CanSerialize4x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create4x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match4x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.HomeTeam); } } }``` Make sure password validation works after saving
```c# namespace Snittlistan.Test { using System.IO; using System.Text; using Models; using Raven.Imports.Newtonsoft.Json; using Xunit; public class SerializationTest : DbTest { [Fact] public void CanSerialize8x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create8x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match8x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.AwayTeam); } [Fact] public void CanSerialize4x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create4x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match4x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.HomeTeam); } [Fact] public void CanSerializeUser() { // Arrange var user = new User("firstName", "lastName", "e@d.com", "some-pass"); // Act using (var session = Store.OpenSession()) { session.Store(user); session.SaveChanges(); } // Assert using (var session = Store.OpenSession()) { var loadedUser = session.Load<User>(user.Id); Assert.True(loadedUser.ValidatePassword("some-pass"), "Password validation failed"); } } } }```
3901d2fd-a380-4042-9c77-c1b71743f8c4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Windows.Data; namespace NuPack.Dialog.PackageManagerUI { public class StringCollectionsToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { IEnumerable<string> parts = (IEnumerable<string>)value; return String.Join(", ", parts); } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } ``` Fix bug in the StringCollection converter when DataServicePackage.Authors is a simple string.
```c# using System; using System.Collections.Generic; using System.Windows.Data; namespace NuPack.Dialog.PackageManagerUI { public class StringCollectionsToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { string stringValue = value as string; if (stringValue != null) { return stringValue; } else { IEnumerable<string> parts = (IEnumerable<string>)value; return String.Join(", ", parts); } } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } ```
6ffba918-9c86-4206-88d7-d6b5e83a9c91
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Wcf 3.0.0")] ``` Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Wcf 3.0.0")] ```
4382fdbc-efff-414c-bd30-1da1086c0e10
{ "language": "C#" }
```c# using UnityEngine; namespace Entitas.Unity.VisualDebugging { public static class GameObjectDestroyExtension { public static void DestroyGameObject(this GameObject gameObject) { #if (UNITY_EDITOR) if (Application.isPlaying) { Object.Destroy(gameObject); } else { Object.DestroyImmediate(gameObject); } #else Destroy(gameObject); #endif } } } ``` Fix Destroy compile time error
```c# using UnityEngine; namespace Entitas.Unity.VisualDebugging { public static class GameObjectDestroyExtension { public static void DestroyGameObject(this GameObject gameObject) { #if (UNITY_EDITOR) if (Application.isPlaying) { Object.Destroy(gameObject); } else { Object.DestroyImmediate(gameObject); } #else Object.Destroy(gameObject); #endif } } } ```
2df0da64-8136-4c49-999a-2edb3654fbd7
{ "language": "C#" }
```c# using CarFuel.DataAccess; using CarFuel.Models; using CarFuel.Services; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CarFuel.Controllers { public class CarsController : Controller { private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex) { TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid id) { var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id); return View(c); } } }``` Handle null id for Cars/Details action
```c# using CarFuel.DataAccess; using CarFuel.Models; using CarFuel.Services; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; namespace CarFuel.Controllers { public class CarsController : Controller { private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex) { TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id); return View(c); } } }```
67b761e3-f3b8-4eac-9375-2918a6c3a16b
{ "language": "C#" }
```c# using Orchard.Data.Migration; namespace Orchard.Users.DataMigrations { public class UsersDataMigration : DataMigrationImpl { public int Create() { //CREATE TABLE Orchard_Users_UserRecord (Id INTEGER not null, UserName TEXT, Email TEXT, NormalizedUserName TEXT, Password TEXT, PasswordFormat TEXT, PasswordSalt TEXT, primary key (Id)); SchemaBuilder.CreateTable("UserRecord", table => table .ContentPartRecord() .Column<string>("UserName") .Column<string>("Email") .Column<string>("NormalizedUserName") .Column<string>("Password") .Column<string>("PasswordFormat") .Column<string>("PasswordSalt") ); return 0010; } } }``` Fix data migration code for UserRecord
```c# using Orchard.Data.Migration; namespace Orchard.Users.DataMigrations { public class UsersDataMigration : DataMigrationImpl { public int Create() { //CREATE TABLE Orchard_Users_UserRecord (Id INTEGER not null, UserName TEXT, Email TEXT, NormalizedUserName TEXT, Password TEXT, PasswordFormat TEXT, PasswordSalt TEXT, primary key (Id)); SchemaBuilder.CreateTable("UserRecord", table => table .ContentPartRecord() .Column<string>("UserName") .Column<string>("Email") .Column<string>("NormalizedUserName") .Column<string>("Password") .Column<string>("PasswordFormat") .Column<string>("HashAlgorithm") .Column<string>("PasswordSalt") ); return 0010; } } }```
fa95c6e2-6429-420c-ae45-0e88c1c2e845
{ "language": "C#" }
```c# using System; namespace CITS.Models { public class MathProblemModel : ProblemModel { public MathProblemModel(string Problem, string Solution):base(Problem,Solution){} public override Boolean IsSolutionCorrect(String candidateSolution) { return Solution.Equals(candidateSolution.Trim()); } } } ``` Support list of hints per problem
```c# using System; using System.Collections.Generic; namespace CITS.Models { public class MathProblemModel : ProblemModel { public MathProblemModel(string problem, string solution, List<String> listOfHints):base(problem,solution, listOfHints){} public override Boolean IsSolutionCorrect(String candidateSolution) { return Solution.Equals(candidateSolution.Trim()); } } } ```
9c256828-9d96-4aac-938e-22ad55fc4644
{ "language": "C#" }
```c# using System; using System.IO; using System.Linq; using NuGet.Frameworks; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.Extensions.DependencyModel.Resolution; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { // The TypeCatalogGen project takes this as input var outputPath = "../TypeCatalogGen/powershell.inc"; // Get a context for our top level project var context = ProjectContext.Create("../Microsoft.PowerShell.CoreConsoleHost", NuGetFramework.Parse("netcoreapp1.0")); System.IO.File.WriteAllLines(outputPath, // Get the target for the current runtime from t in context.LockFile.Targets where t.RuntimeIdentifier == Constants.RuntimeIdentifier // Get the packages (not projects) from x in t.Libraries where x.Type == "package" // Get the real reference assemblies from y in x.CompileTimeAssemblies where y.Path.EndsWith(".dll") // Construct the path to the assemblies select $"{context.PackagesDirectory}/{x.Name}/{x.Version}/{y.Path};"); Console.WriteLine($"List of reference assemblies written to {outputPath}"); } } } ``` Update TypeCatalogParser for CoreConsoleHost removal
```c# using System; using System.IO; using System.Linq; using NuGet.Frameworks; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.Extensions.DependencyModel.Resolution; namespace TypeCatalogParser { public class Program { public static void Main(string[] args) { // The TypeCatalogGen project takes this as input var outputPath = "../TypeCatalogGen/powershell.inc"; // Get a context for our top level project var context = ProjectContext.Create("../powershell", NuGetFramework.Parse("netcoreapp1.0")); System.IO.File.WriteAllLines(outputPath, // Get the target for the current runtime from t in context.LockFile.Targets where t.RuntimeIdentifier == Constants.RuntimeIdentifier // Get the packages (not projects) from x in t.Libraries where x.Type == "package" // Get the real reference assemblies from y in x.CompileTimeAssemblies where y.Path.EndsWith(".dll") // Construct the path to the assemblies select $"{context.PackagesDirectory}/{x.Name}/{x.Version}/{y.Path};"); Console.WriteLine($"List of reference assemblies written to {outputPath}"); } } } ```
f4b0a42e-81dd-4d2c-9d5c-6590285d7cc4
{ "language": "C#" }
```c#  using UnityEngine; using UnityEngine.EventSystems; class DisableMouse : MonoBehaviour { // private stuff we don't want the editor to see private GameObject m_lastSelectedGameObject; // this is called by unity before start void Awake() { m_lastSelectedGameObject = new GameObject(); } // this is called by unity every frame void Update() { // check if we have an active ui if ( EventSystem.current != null ) { // check if we have a currently selected game object if ( EventSystem.current.currentSelectedGameObject == null ) { // nope - the mouse may have stolen it - give it back to the last selected game object EventSystem.current.SetSelectedGameObject( m_lastSelectedGameObject ); } else if ( EventSystem.current.currentSelectedGameObject != m_lastSelectedGameObject ) { // we changed our selection - remember it m_lastSelectedGameObject = EventSystem.current.currentSelectedGameObject; } } } } ``` Disable the disable mouse script for now
```c#  using UnityEngine; using UnityEngine.EventSystems; class DisableMouse : MonoBehaviour { // private stuff we don't want the editor to see private GameObject m_lastSelectedGameObject; // this is called by unity before start void Awake() { m_lastSelectedGameObject = new GameObject(); } // this is called by unity every frame void Update() { // check if we have an active ui if ( false && ( EventSystem.current != null ) ) { // check if we have a currently selected game object if ( EventSystem.current.currentSelectedGameObject == null ) { // nope - the mouse may have stolen it - give it back to the last selected game object EventSystem.current.SetSelectedGameObject( m_lastSelectedGameObject ); } else if ( EventSystem.current.currentSelectedGameObject != m_lastSelectedGameObject ) { // we changed our selection - remember it m_lastSelectedGameObject = EventSystem.current.currentSelectedGameObject; } } } } ```
efe8eda7-0ff5-48ce-821a-826afe4a365f
{ "language": "C#" }
```c# using com.techphernalia.MyPersonalAccounts.Model.Inventory; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace com.techphernalia.MyPersonalAccounts.Model.Controller { public interface IInventoryController { #region Stock Unit List<StockUnit> GetAllStockUnits(); StockUnit GetStockUnitFromId(int unitId); int AddStockUnit(StockUnit stockUnit); bool UpdateStockUnit(StockUnit stockUnit); bool DeleteStockUnit(int unitId); #endregion #region Stock Group List<StockGroup> GetAllStockGroups(); List<StockGroup> GetStockGroupsForGroup(int stockGroupId); StockGroup GetStockGroupFromId(int stockGroupId); int AddStockGroup(StockItem stockItem); bool UpdateStockGroup(StockItem stockItem); bool DeleteStockGroup(int stockGroupId); #endregion #region Stock Item List<StockItem> GetAllStockItems(); List<StockItem> GetStockItemsForGroup(int stockGroupId); StockItem GetStockItemFromId(int stockItemId); int AddStockItem(StockGroup stockGroup); bool UpdateStockItem(StockGroup stockGroup); bool DeleteStockItemI(int stockItemId); #endregion } } ``` Update interface for return type
```c# using com.techphernalia.MyPersonalAccounts.Model.Inventory; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace com.techphernalia.MyPersonalAccounts.Model.Controller { public interface IInventoryController { #region Stock Unit List<StockUnit> GetAllStockUnits(); StockUnit GetStockUnitFromId(int unitId); int AddStockUnit(StockUnit stockUnit); void UpdateStockUnit(StockUnit stockUnit); void DeleteStockUnit(int unitId); #endregion #region Stock Group List<StockGroup> GetAllStockGroups(); List<StockGroup> GetStockGroupsForGroup(int stockGroupId); StockGroup GetStockGroupFromId(int stockGroupId); int AddStockGroup(StockItem stockItem); bool UpdateStockGroup(StockItem stockItem); bool DeleteStockGroup(int stockGroupId); #endregion #region Stock Item List<StockItem> GetAllStockItems(); List<StockItem> GetStockItemsForGroup(int stockGroupId); StockItem GetStockItemFromId(int stockItemId); int AddStockItem(StockGroup stockGroup); bool UpdateStockItem(StockGroup stockGroup); bool DeleteStockItemI(int stockItemId); #endregion } } ```
c6c1b482-b548-4305-b368-0d720c47ce10
{ "language": "C#" }
```c# namespace TraktApiSharp.Objects.Get.Shows.Episodes { using Basic; public class TraktEpisodeIds : TraktIds { } } ``` Add documentation for episode ids.
```c# namespace TraktApiSharp.Objects.Get.Shows.Episodes { using Basic; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt episode.</summary> public class TraktEpisodeIds : TraktIds { } } ```
f444693f-991f-4e22-8133-78a2b58d4b4d
{ "language": "C#" }
```c# namespace GeekLearning.Domain.AspnetCore { using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; public class DomainExceptionFilter : IActionFilter { private ILoggerFactory loggerFactory; private IOptions<DomainOptions> options; public DomainExceptionFilter(ILoggerFactory loggerFactory, IOptions<DomainOptions> domainOptions) { this.loggerFactory = loggerFactory; this.options = domainOptions; } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception != null) { var domainException = context.Exception as DomainException; var logger = this.loggerFactory.CreateLogger<DomainExceptionFilter>(); if (domainException == null) { logger.LogError(new EventId(1, "Unknown error"), context.Exception.Message, context.Exception); domainException = new Explanations.Unknown().AsException(context.Exception); } context.Result = new MaybeResult<object>(domainException.Explanation); context.ExceptionHandled = true; } } public void OnActionExecuting(ActionExecutingContext context) { } } } ``` Fix DomainException LogError parameter order
```c# namespace GeekLearning.Domain.AspnetCore { using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; public class DomainExceptionFilter : IActionFilter { private ILoggerFactory loggerFactory; private IOptions<DomainOptions> options; public DomainExceptionFilter(ILoggerFactory loggerFactory, IOptions<DomainOptions> domainOptions) { this.loggerFactory = loggerFactory; this.options = domainOptions; } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception != null) { var domainException = context.Exception as DomainException; var logger = this.loggerFactory.CreateLogger<DomainExceptionFilter>(); if (domainException == null) { logger.LogError(new EventId(1, "Unknown error"), context.Exception, context.Exception.Message); domainException = new Explanations.Unknown().AsException(context.Exception); } context.Result = new MaybeResult<object>(domainException.Explanation); context.ExceptionHandled = true; } } public void OnActionExecuting(ActionExecutingContext context) { } } } ```
102c3592-c27b-4d25-bb0c-cc89f6d20159
{ "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; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Users; using osu.Game.Rulesets.Replays; namespace osu.Game.Rulesets.Scoring { public class Score { public ScoreRank Rank { get; set; } public double TotalScore { get; set; } public double Accuracy { get; set; } public double Health { get; set; } = 1; public double? PP { get; set; } public int MaxCombo { get; set; } public int Combo { get; set; } public RulesetInfo Ruleset { get; set; } public Mod[] Mods { get; set; } = { }; public User User; public Replay Replay; public BeatmapInfo Beatmap; public long OnlineScoreID; public DateTimeOffset Date; public Dictionary<HitResult, object> Statistics = new Dictionary<HitResult, object>(); } } ``` Fix score retrieval no longer working
```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; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Users; using osu.Game.Rulesets.Replays; namespace osu.Game.Rulesets.Scoring { public class Score { public ScoreRank Rank { get; set; } public double TotalScore { get; set; } public double Accuracy { get; set; } public double Health { get; set; } = 1; public double? PP { get; set; } public int MaxCombo { get; set; } public int Combo { get; set; } public RulesetInfo Ruleset { get; set; } public Mod[] Mods { get; set; } = { }; public User User; [JsonIgnore] public Replay Replay; public BeatmapInfo Beatmap; public long OnlineScoreID; public DateTimeOffset Date; public Dictionary<HitResult, object> Statistics = new Dictionary<HitResult, object>(); } } ```
ce709e59-923a-4b8c-ac8e-d24ea1c5392c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace xwalk { class TwoinoneTest { static void Main(string[] args) { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); bool isTabletEmulated = monitor.IsTablet; // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); isTabletEmulated = !isTabletEmulated; emulator.IsTablet = isTabletEmulated; } } } private static void onTabletModeChanged(bool isTablet) { Console.WriteLine("onTabletModeChanged: " + isTablet); } } } ``` Enable testing in emulated or actual device mode
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace xwalk { class TwoinoneTest { static void Main(string[] args) { if (args.Length > 0 && args[0] == "emulator") { runEmulator(); } else { run(); } } static void run() { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); Console.WriteLine("Tablet mode " + monitor.IsTablet); } } } static void runEmulator() { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); bool isTabletEmulated = monitor.IsTablet; // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); isTabletEmulated = !isTabletEmulated; emulator.IsTablet = isTabletEmulated; } } } private static void onTabletModeChanged(bool isTablet) { Console.WriteLine("onTabletModeChanged: " + isTablet); } } } ```
8b1bfc15-49dc-48f3-8c28-46095500e87e
{ "language": "C#" }
```c# using Lbookshelf.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Interactivity; namespace Lbookshelf.Utils { public class ChangeThumbnailBehavior : Behavior<FrameworkElement> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseLeftButtonUp += ShowChooseThumbnailDialog; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseLeftButtonUp -= ShowChooseThumbnailDialog; } private void ShowChooseThumbnailDialog(object sender, System.Windows.Input.MouseButtonEventArgs e) { DialogService.ShowOpenFileDialog( fileName => { // Note that when editing a book, we are actually // editing a clone of the original book. // The changes can be safely discarded if the user // cancel the edit. So feel free to change the // value of Thumbnail. The BookManager is responsible // for copying the new thumbnail. var book = (Book)AssociatedObject.DataContext; book.Thumbnail = fileName; }, "Image files|*.jpg", ".jpg"); } } } ``` Enable the user to choose PNG file as thumbnail.
```c# using Lbookshelf.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Interactivity; namespace Lbookshelf.Utils { public class ChangeThumbnailBehavior : Behavior<FrameworkElement> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseLeftButtonUp += ShowChooseThumbnailDialog; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseLeftButtonUp -= ShowChooseThumbnailDialog; } private void ShowChooseThumbnailDialog(object sender, System.Windows.Input.MouseButtonEventArgs e) { DialogService.ShowOpenFileDialog( fileName => { // Note that when editing a book, we are actually // editing a clone of the original book. // The changes can be safely discarded if the user // cancel the edit. So feel free to change the // value of Thumbnail. The BookManager is responsible // for copying the new thumbnail. var book = (Book)AssociatedObject.DataContext; book.Thumbnail = fileName; }, "Image files|*.jpg;*.png", ".jpg"); } } } ```
2bb8c019-16ae-456c-be71-a549b7659366
{ "language": "C#" }
```c# // Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace MiniCube { /// <summary> /// Simple MiniCube application using SharpDX.Toolkit. /// </summary> class Program { /// <summary> /// Defines the entry point of the application. /// </summary> #if NETFX_CORE [MTAThread] #else [STAThread] #endif static void Main() { using (var program = new SphereGame()) program.Run(); } } } ``` Fix compilation error in sample
```c# // Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace MiniCube { /// <summary> /// Simple MiniCube application using SharpDX.Toolkit. /// </summary> class Program { /// <summary> /// Defines the entry point of the application. /// </summary> #if NETFX_CORE [MTAThread] #else [STAThread] #endif static void Main() { using (var program = new MiniCubeGame()) program.Run(); } } } ```
f8e4852b-cbb1-4d46-8d63-a9d39c5ec5d1
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NBi.Core.Analysis.Metadata { public class Property : IField { public string UniqueName { get; private set; } public string Caption { get; set; } public Property(string uniqueName, string caption) { UniqueName = uniqueName; Caption = caption; } public Property Clone() { return new Property(UniqueName, Caption); } } } ``` Add method ToString to override default display and replace by Caption
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NBi.Core.Analysis.Metadata { public class Property : IField { public string UniqueName { get; private set; } public string Caption { get; set; } public Property(string uniqueName, string caption) { UniqueName = uniqueName; Caption = caption; } public Property Clone() { return new Property(UniqueName, Caption); } public override string ToString() { return Caption.ToString(); } } } ```
f6504c83-ca06-412d-85f6-6c5d5ebd41c8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NXTLib; using System.IO; namespace nxtlibtester { class Program { static void Main(string[] args) { try { string filename = "version.ric"; //filename on disk (locally) string filenameonbrick = "version.ric"; //filename on remote NXT //Prepare Connection Console.WriteLine("File Upload Test\r\n"); Console.WriteLine("Connecting to brick..."); Brick brick = new Brick(Brick.LinkType.USB, null); //Brick = top layer of code, contains the sensors and motors if (!brick.Connect()) { throw new Exception(brick.LastError); } Protocol protocol = brick.ProtocolLink; //Protocol = underlying layer of code, contains NXT communications //Test Connection if (!brick.IsConnected) { throw new Exception("Not connected to NXT!"); } //Upload File Console.WriteLine("Uploading file..."); if (!brick.UploadFile(filename, filenameonbrick)) { throw new Exception(brick.LastError); } Console.WriteLine("Success!"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } } } } ``` Add test files to tree
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NXTLib; using System.IO; namespace nxtlibtester { class Program { static void Main(string[] args) { try { string filename = "../../version.ric"; //filename on disk (locally) string filenameonbrick = "version.ric"; //filename on remote NXT //Prepare Connection Console.WriteLine("File Upload Test\r\n"); Console.WriteLine("Connecting to brick..."); Brick brick = new Brick(Brick.LinkType.USB, null); //Brick = top layer of code, contains the sensors and motors if (!brick.Connect()) { throw new Exception(brick.LastError); } Protocol protocol = brick.ProtocolLink; //Protocol = underlying layer of code, contains NXT communications //Test Connection if (!brick.IsConnected) { throw new Exception("Not connected to NXT!"); } //Upload File Console.WriteLine("Uploading file..."); if (!brick.UploadFile(filename, filenameonbrick)) { throw new Exception(brick.LastError); } Console.WriteLine("Success!"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } } } } ```
869e7ce0-9b54-4774-ad40-6f55f2bad8fe
{ "language": "C#" }
```c# namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Platform { using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Xunit.Assert; [TestClass] public class PlatformReferencesTests { [TestMethod] public void NoSystemWebReferences() { // Validate Platform assembly. foreach (var assembly in typeof(DebugOutput).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } // Validate Core assembly foreach (var assembly in typeof(EventTelemetry).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } } } } ``` Revert "Dummy commit to test PR. No real changes"
```c# namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Platform { using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Xunit.Assert; [TestClass] public class PlatformReferencesTests { [TestMethod] public void NoSystemWebReferences() { // Validate Platform assembly foreach (var assembly in typeof(DebugOutput).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } // Validate Core assembly foreach (var assembly in typeof(EventTelemetry).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } } } } ```
7aa3ca3e-9058-4ee3-8d66-179b351871cd
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private private partial class KeyValueListNode { } private static readonly string FieldKey = $"{typeof(Activity).FullName}"; #endregion } }``` Mark Activity and it's properties as Serializable
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { // this code is specific to .NET 4.5 and uses CallContext to store Activity.Current which requires Activity to be Serializable. [Serializable] // DO NOT remove public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private [Serializable] // DO NOT remove private partial class KeyValueListNode { } private static readonly string FieldKey = $"{typeof(Activity).FullName}"; #endregion } }```
f403ddaf-d05d-4dcd-b79b-85f77ed6e388
{ "language": "C#" }
```c# using System.Linq; using Xunit; namespace Microsoft.Language.Xml.Tests { public class TestApi { [Fact] public void TestAttributeValue() { var root = Parser.ParseText("<e a=\"\"/>"); var attributeValue = root.Attributes.First().Value; Assert.Equal("", attributeValue); } [Fact] public void TestContent() { var root = Parser.ParseText("<e>Content</e>"); var value = root.Value; Assert.Equal("Content", value); } } } ``` Add some tests for a bug.
```c# using System.Linq; using Xunit; namespace Microsoft.Language.Xml.Tests { public class TestApi { [Fact] public void TestAttributeValue() { var root = Parser.ParseText("<e a=\"\"/>"); var attributeValue = root.Attributes.First().Value; Assert.Equal("", attributeValue); } [Fact] public void TestContent() { var root = Parser.ParseText("<e>Content</e>"); var value = root.Value; Assert.Equal("Content", value); } [Fact] public void TestRootLevel() { var root = Parser.ParseText("<Root></Root>"); Assert.Equal("Root", root.Name); } [Fact(Skip = "https://github.com/KirillOsenkov/XmlParser/issues/8")] public void TestRootLevelTrivia() { var root = Parser.ParseText("<!-- C --><Root></Root>"); Assert.Equal("Root", root.Name); } [Fact] public void TestRootLevelTriviaWithDeclaration() { var root = Parser.ParseText("<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- C --><Root></Root>"); Assert.Equal("Root", root.Name); } } } ```
eb11ade0-960b-4de5-a4a1-78d57cb21917
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyCompany("Andrew Davey")] [assembly: AssemblyProduct("Cassette")] [assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")] // NOTE: When changing this version, also update Cassette.MSBuild\Cassette.targets to match. [assembly: AssemblyInformationalVersion("2.0.0")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyFileVersion("2.0.0.0")]``` Set nuget package version to 2.0.0-beta1
```c# using System.Reflection; [assembly: AssemblyCompany("Andrew Davey")] [assembly: AssemblyProduct("Cassette")] [assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")] [assembly: AssemblyInformationalVersion("2.0.0-beta1")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyFileVersion("2.0.0.0")]```
3e733c96-2829-4262-b59c-f87be700df12
{ "language": "C#" }
```c# namespace DotnetThoughts.AspNet { using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using System.IO; using System.Threading.Tasks; using System.Text; using System.Text.RegularExpressions; public class HtmlMinificationMiddleware { private RequestDelegate _next; public HtmlMinificationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var stream = context.Response.Body; using (var buffer = new MemoryStream()) { context.Response.Body = buffer; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); buffer.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(buffer)) { string responseBody = await reader.ReadToEndAsync(); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { responseBody = Regex.Replace(responseBody, @">\s+<", "><", RegexOptions.Compiled); } using (var memoryStream = new MemoryStream()) { var bytes = Encoding.UTF8.GetBytes(responseBody); memoryStream.Write(bytes, 0, bytes.Length); memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(stream, bytes.Length); } } } } } }``` Support added for HTML comment removal
```c# namespace DotnetThoughts.AspNet { using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using System.IO; using System.Threading.Tasks; using System.Text; using System.Text.RegularExpressions; public class HtmlMinificationMiddleware { private RequestDelegate _next; public HtmlMinificationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var stream = context.Response.Body; using (var buffer = new MemoryStream()) { context.Response.Body = buffer; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); buffer.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(buffer)) { string responseBody = await reader.ReadToEndAsync(); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { responseBody = Regex.Replace(responseBody, @">\s+<", "><", RegexOptions.Compiled); responseBody = Regex.Replace(responseBody, @"<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->)(.|\n))*-->", "", RegexOptions.Compiled); } using (var memoryStream = new MemoryStream()) { var bytes = Encoding.UTF8.GetBytes(responseBody); memoryStream.Write(bytes, 0, bytes.Length); memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(stream, bytes.Length); } } } } } } ```
8ca3da87-ca07-411a-b52a-493131216146
{ "language": "C#" }
```c# using LogicalShift.Reason.Api; using LogicalShift.Reason.Clauses; using System; using System.Linq; namespace LogicalShift.Reason { /// <summary> /// Methods for creating an altering clauses /// </summary> public static class Clause { /// <summary> /// Creates a new negative Horn clause /// </summary> public static IClause If(params ILiteral[] literals) { if (literals == null) throw new ArgumentNullException("literals"); if (literals.Any(literal => literal == null)) throw new ArgumentException("Null literals are not allowed", "literals"); return new NegativeClause(literals); } /// <summary> /// Adds a positive literal to a negative Horn clause /// </summary> public static IClause Then(this IClause negativeHornClause, ILiteral then) { if (negativeHornClause == null) throw new ArgumentNullException("negativeHornClause"); if (negativeHornClause.Implies != null) throw new ArgumentException("Clause already has an implication", "negativeHornClause"); if (then == null) throw new ArgumentNullException("then"); return new PositiveClause(negativeHornClause, then); } /// <summary> /// Returns a clause indicating that a literal is unconditionally true /// </summary> public static IClause Always(ILiteral always) { return If(Literal.True()).Then(always); } } } ``` Change Always(x) so that it doesn't depend on the 'true' literal
```c# using LogicalShift.Reason.Api; using LogicalShift.Reason.Clauses; using System; using System.Linq; namespace LogicalShift.Reason { /// <summary> /// Methods for creating an altering clauses /// </summary> public static class Clause { /// <summary> /// Creates a new negative Horn clause /// </summary> public static IClause If(params ILiteral[] literals) { if (literals == null) throw new ArgumentNullException("literals"); if (literals.Any(literal => literal == null)) throw new ArgumentException("Null literals are not allowed", "literals"); return new NegativeClause(literals); } /// <summary> /// Adds a positive literal to a negative Horn clause /// </summary> public static IClause Then(this IClause negativeHornClause, ILiteral then) { if (negativeHornClause == null) throw new ArgumentNullException("negativeHornClause"); if (negativeHornClause.Implies != null) throw new ArgumentException("Clause already has an implication", "negativeHornClause"); if (then == null) throw new ArgumentNullException("then"); return new PositiveClause(negativeHornClause, then); } /// <summary> /// Returns a clause indicating that a literal is unconditionally true /// </summary> public static IClause Always(ILiteral always) { return If().Then(always); } } } ```
3c628c84-e3b1-4743-88dc-c6f5a0d114ce
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; namespace osu.Framework.Statistics { public class GlobalStatistic<T> : IGlobalStatistic { public string Group { get; } public string Name { get; } public IBindable<string> DisplayValue => displayValue; private readonly Bindable<string> displayValue = new Bindable<string>(); public Bindable<T> Bindable { get; } = new Bindable<T>(); public T Value { get => Bindable.Value; set => Bindable.Value = value; } public GlobalStatistic(string group, string name) { Group = group; Name = name; Bindable.ValueChanged += val => displayValue.Value = val.NewValue.ToString(); } public virtual void Clear() => Bindable.SetDefault(); } } ``` Fix initial value not propagating
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; namespace osu.Framework.Statistics { public class GlobalStatistic<T> : IGlobalStatistic { public string Group { get; } public string Name { get; } public IBindable<string> DisplayValue => displayValue; private readonly Bindable<string> displayValue = new Bindable<string>(); public Bindable<T> Bindable { get; } = new Bindable<T>(); public T Value { get => Bindable.Value; set => Bindable.Value = value; } public GlobalStatistic(string group, string name) { Group = group; Name = name; Bindable.BindValueChanged(val => displayValue.Value = val.NewValue.ToString(), true); } public virtual void Clear() => Bindable.SetDefault(); } } ```
4606b80e-cfb7-4976-bdb0-7b967a97f079
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using OpenQA.Selenium; using Selenium.Internal.SeleniumEmulation; namespace Selenium.Internal.SeleniumEmulation { /// <summary> /// Defines the command for the open keyword. /// </summary> internal class Open : SeleneseCommand { private Uri baseUrl; /// <summary> /// Initializes a new instance of the <see cref="Open"/> class. /// </summary> /// <param name="baseUrl">The base URL to open with the command.</param> public Open(Uri baseUrl) { this.baseUrl = baseUrl; } /// <summary> /// Handles the command. /// </summary> /// <param name="driver">The driver used to execute the command.</param> /// <param name="locator">The first parameter to the command.</param> /// <param name="value">The second parameter to the command.</param> /// <returns>The result of the command.</returns> protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { string urlToOpen = this.ConstructUrl(locator); driver.Url = urlToOpen; return null; } private string ConstructUrl(string path) { string urlToOpen = path.Contains("://") ? path : this.baseUrl.ToString() + (!path.StartsWith("/", StringComparison.Ordinal) ? "/" : string.Empty) + path; return urlToOpen; } } } ``` Remove trailing slashes from baseUrl in .NET to prevent double slashes in URL
```c# using System; using System.Collections.Generic; using System.Text; using OpenQA.Selenium; using Selenium.Internal.SeleniumEmulation; namespace Selenium.Internal.SeleniumEmulation { /// <summary> /// Defines the command for the open keyword. /// </summary> internal class Open : SeleneseCommand { private Uri baseUrl; /// <summary> /// Initializes a new instance of the <see cref="Open"/> class. /// </summary> /// <param name="baseUrl">The base URL to open with the command.</param> public Open(Uri baseUrl) { this.baseUrl = baseUrl; } /// <summary> /// Handles the command. /// </summary> /// <param name="driver">The driver used to execute the command.</param> /// <param name="locator">The first parameter to the command.</param> /// <param name="value">The second parameter to the command.</param> /// <returns>The result of the command.</returns> protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { string urlToOpen = this.ConstructUrl(locator); driver.Url = urlToOpen; return null; } private string ConstructUrl(string path) { string urlToOpen = path.Contains("://") ? path : this.baseUrl.ToString().TrimEnd('/') + (!path.StartsWith("/", StringComparison.Ordinal) ? "/" : string.Empty) + path; return urlToOpen; } } } ```
8e5ba7b4-54c8-46c3-91a3-dcb319eb189c
{ "language": "C#" }
```c# // Copyright(c) 2016 Google 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.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { // GET: Session/Login public ActionResult Login() { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] // GET: Session/Logout public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } } ``` Add comment to Auth Login action describing redirect
```c# // Copyright(c) 2016 Google 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.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public ActionResult Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } } ```
c39d4dac-657b-4a09-b472-e68f395caa03
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace SpotifyAPI.Web { public static class Util { public static string GetStringAttribute<T>(this T en, String separator) where T : struct, IConvertible { Enum e = (Enum)(object)en; IEnumerable<StringAttribute> attributes = Enum.GetValues(typeof(T)) .Cast<T>() .Where(v => e.HasFlag((Enum)(object)v)) .Select(v => typeof(T).GetField(v.ToString(CultureInfo.InvariantCulture))) .Select(f => f.GetCustomAttributes(typeof(StringAttribute), false)[0]) .Cast<StringAttribute>(); List<String> list = new List<String>(); attributes.ToList().ForEach(element => list.Add(element.Text)); return string.Join(" ", list); } } public sealed class StringAttribute : Attribute { public String Text { get; set; } public StringAttribute(String text) { Text = text; } } }``` Use separator when joining string attributes
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace SpotifyAPI.Web { public static class Util { public static string GetStringAttribute<T>(this T en, String separator) where T : struct, IConvertible { Enum e = (Enum)(object)en; IEnumerable<StringAttribute> attributes = Enum.GetValues(typeof(T)) .Cast<T>() .Where(v => e.HasFlag((Enum)(object)v)) .Select(v => typeof(T).GetField(v.ToString(CultureInfo.InvariantCulture))) .Select(f => f.GetCustomAttributes(typeof(StringAttribute), false)[0]) .Cast<StringAttribute>(); List<String> list = new List<String>(); attributes.ToList().ForEach(element => list.Add(element.Text)); return string.Join(separator, list); } } public sealed class StringAttribute : Attribute { public String Text { get; set; } public StringAttribute(String text) { Text = text; } } } ```
c2e603bf-d385-45bc-b652-3d005a361821
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HermaFx.Settings { [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = false)] public sealed class SettingsAttribute : Attribute { public const string DEFAULT_PREFIX_SEPARATOR = ":"; /// <summary> /// Gets or sets the key prefix. /// </summary> /// <value> /// The key prefix. /// </value> public string KeyPrefix { get; } /// <summary> /// Gets or sets the prefix separator. /// </summary> /// <value> /// The prefix separator. /// </value> public string PrefixSeparator { get; set; } public SettingsAttribute() { PrefixSeparator = DEFAULT_PREFIX_SEPARATOR; } public SettingsAttribute(string keyPrefix) : this() { KeyPrefix = keyPrefix; } } } ``` Implement IPropertyDescriptorInitializer to validate properties on initializing
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Castle.Components.DictionaryAdapter; namespace HermaFx.Settings { [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = false)] public sealed class SettingsAttribute : Attribute, IPropertyDescriptorInitializer { public const string DEFAULT_PREFIX_SEPARATOR = ":"; /// <summary> /// Gets or sets the key prefix. /// </summary> /// <value> /// The key prefix. /// </value> public string KeyPrefix { get; } /// <summary> /// Gets or sets the prefix separator. /// </summary> /// <value> /// The prefix separator. /// </value> public string PrefixSeparator { get; set; } public SettingsAttribute() { PrefixSeparator = DEFAULT_PREFIX_SEPARATOR; } public SettingsAttribute(string keyPrefix) : this() { KeyPrefix = keyPrefix; } #region IPropertyDescriptorInitializer public int ExecutionOrder => DictionaryBehaviorAttribute.LastExecutionOrder; public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors) { propertyDescriptor.Fetch = true; } public IDictionaryBehavior Copy() { return this; } #endregion } } ```
cf946b48-2811-45ee-9930-e62d489a1343
{ "language": "C#" }
```c# using System; static class Program { static int RemoveDupes(this int[] a) { int write = 1; int read = 0; bool same = false; int count = 0; for (int i = 1; i < a.Length; i++) { read = i; if (same && a[read] == a[write]) { count++; continue; } same = a[read] == a[write]; a[write++] = a[read]; } return a.Length - count; } static void Main() { int[] a = new int[] {1, 1, 1, 2, 2, 3, 3, 3}; int c = RemoveDupes(a); for (int i = 0; i < c; i++) { Console.Write("{0} ", a[i]); } Console.WriteLine(); } } ``` Remove duplicates from sorted array II - Linq
```c# using System; using System.Linq; using System.Collections.Generic; static class Program { static int RemoveDupes(this int[] a) { int write = 1; int read = 0; bool same = false; int count = 0; for (int i = 1; i < a.Length; i++) { read = i; if (same && a[read] == a[write]) { count++; continue; } same = a[read] == a[write]; a[write++] = a[read]; } return a.Length - count; } static int[] RemoveDupes2(this int[] v) { return v.Aggregate(new List<int>(), (a, b) => { if (a.Count(x => x == b) < 2) { a.Add(b); } return a; }).ToArray(); } static void Main() { int[] a = new int[] {1, 1, 1, 2, 2, 3, 3, 3}; int c = RemoveDupes(a); for (int i = 0; i < c; i++) { Console.Write("{0} ", a[i]); } Console.WriteLine(); foreach (int x in RemoveDupes2(a)) { Console.Write("{0} ", x); } Console.WriteLine(); } } ```
93d6174a-a968-4a6d-a539-f73bf071df0e
{ "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 System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using osu.Framework.Configuration; using osu.Game.Modes.Objects.Drawables; namespace osu.Game.Modes { public class ScoreProcessor { public virtual Score GetScore() => new Score(); public BindableDouble TotalScore = new BindableDouble { MinValue = 0 }; public BindableDouble Accuracy = new BindableDouble { MinValue = 0, MaxValue = 1 }; public BindableInt Combo = new BindableInt(); public List<JudgementInfo> Judgements = new List<JudgementInfo>(); public virtual void AddJudgement(JudgementInfo judgement) { Judgements.Add(judgement); UpdateCalculations(); judgement.ComboAtHit = (ulong)Combo.Value; } /// <summary> /// Update any values that potentially need post-processing on a judgement change. /// </summary> protected virtual void UpdateCalculations() { } } } ``` Store max combo in ScoreProcessor.
```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 System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using osu.Framework.Configuration; using osu.Game.Modes.Objects.Drawables; namespace osu.Game.Modes { public class ScoreProcessor { public virtual Score GetScore() => new Score(); public BindableDouble TotalScore = new BindableDouble { MinValue = 0 }; public BindableDouble Accuracy = new BindableDouble { MinValue = 0, MaxValue = 1 }; public BindableInt Combo = new BindableInt(); public BindableInt MaximumCombo = new BindableInt(); public List<JudgementInfo> Judgements = new List<JudgementInfo>(); public virtual void AddJudgement(JudgementInfo judgement) { Judgements.Add(judgement); UpdateCalculations(); judgement.ComboAtHit = (ulong)Combo.Value; if (Combo.Value > MaximumCombo.Value) MaximumCombo.Value = Combo.Value; } /// <summary> /// Update any values that potentially need post-processing on a judgement change. /// </summary> protected virtual void UpdateCalculations() { } } } ```