doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
60cf7699-9f25-4ab0-8389-46d289759462
{ "language": "C#" }
```c# using System; using System.Linq; using System.Threading.Tasks; using Bug2211; using Marten; using Marten.Testing.Harness; using Shouldly; using Weasel.Core; using Xunit; namespace DocumentDbTests.Bugs { public class Bug_2211_select_transform_inner_object: BugIntegrationContext { [Fact] public async Task should_be_able_to_select_nested_objects() { using var documentStore = SeparateStore(x => { x.AutoCreateSchemaObjects = AutoCreate.All; x.Schema.For<TestEntity>(); }); await documentStore.Advanced.Clean.DeleteAllDocumentsAsync(); await using var session = documentStore.OpenSession(); session.Store(new TestEntity { Name = "Test", Inner = new TestDto { Name = "TestDto" } }); await session.SaveChangesAsync(); await using var querySession = documentStore.QuerySession(); var results = await querySession.Query<TestEntity>() .Select(x => new { Inner = x.Inner }) .ToListAsync(); results.Count.ShouldBe(1); results[0].Inner.Name.ShouldBe("Test Dto"); } } } namespace Bug2211 { public class TestEntity { public Guid Id { get; set; } public string Name { get; set; } public TestDto Inner { get; set; } } public class TestDto { public string Name { get; set; } } } ``` Fix test referring to wrong value
```c# using System; using System.Linq; using System.Threading.Tasks; using Bug2211; using Marten; using Marten.Testing.Harness; using Shouldly; using Weasel.Core; using Xunit; namespace DocumentDbTests.Bugs { public class Bug_2211_select_transform_inner_object: BugIntegrationContext { [Fact] public async Task should_be_able_to_select_nested_objects() { using var documentStore = SeparateStore(x => { x.AutoCreateSchemaObjects = AutoCreate.All; x.Schema.For<TestEntity>(); }); await documentStore.Advanced.Clean.DeleteAllDocumentsAsync(); await using var session = documentStore.OpenSession(); var testEntity = new TestEntity { Name = "Test", Inner = new TestDto { Name = "TestDto" } }; session.Store(testEntity); await session.SaveChangesAsync(); await using var querySession = documentStore.QuerySession(); var results = await querySession.Query<TestEntity>() .Select(x => new { Inner = x.Inner }) .ToListAsync(); results.Count.ShouldBe(1); results[0].Inner.Name.ShouldBe(testEntity.Inner.Name); } } } namespace Bug2211 { public class TestEntity { public Guid Id { get; set; } public string Name { get; set; } public TestDto Inner { get; set; } } public class TestDto { public string Name { get; set; } } } ```
6f212a2a-2748-48d0-b3fb-c2415230e2e1
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; using UnityEngine; namespace LiteNetLibHighLevel { public class ServerSpawnSceneObjectMessage : LiteNetLibMessageBase { public uint objectId; public Vector3 position; public override void Deserialize(NetDataReader reader) { objectId = reader.GetUInt(); position = new Vector3(reader.GetFloat(), reader.GetFloat(), reader.GetFloat()); } public override void Serialize(NetDataWriter writer) { writer.Put(objectId); writer.Put(position.x); writer.Put(position.y); writer.Put(position.z); } } } ``` Change serialize/deserialze abstract class to interface
```c# using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; using UnityEngine; namespace LiteNetLibHighLevel { public class ServerSpawnSceneObjectMessage : ILiteNetLibMessage { public uint objectId; public Vector3 position; public void Deserialize(NetDataReader reader) { objectId = reader.GetUInt(); position = new Vector3(reader.GetFloat(), reader.GetFloat(), reader.GetFloat()); } public void Serialize(NetDataWriter writer) { writer.Put(objectId); writer.Put(position.x); writer.Put(position.y); writer.Put(position.z); } } } ```
80ec8afb-01e9-438f-a0b4-c4747db5e5df
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18449 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyVersion("1.0.*")] [assembly: System.Reflection.AssemblyInformationalVersion("0.1.2")] ``` Set correct version number, v0.1.1
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18449 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyVersion("1.0.*")] [assembly: System.Reflection.AssemblyInformationalVersion("0.1.1")] ```
6da40569-863f-4b9a-984b-ddec441ae8a6
{ "language": "C#" }
```c# using UnityEngine; namespace Pear.InteractionEngine.Converters { /// <summary> /// Converts a Vector2 to Vector3 /// </summary> public class Vector2ToVector3 : MonoBehaviour, IPropertyConverter<Vector2, Vector3> { public Vector3 Convert(Vector2 convertFrom) { return convertFrom; } } } ``` Add more features to vector 2 -> vector 3 conversion
```c# using System; using System.Collections.Generic; using UnityEngine; namespace Pear.InteractionEngine.Converters { /// <summary> /// Converts a Vector2 to Vector3 /// </summary> public class Vector2ToVector3 : MonoBehaviour, IPropertyConverter<Vector2, Vector3> { [Tooltip("Where should the X value be set")] public VectorFields SetXOn = VectorFields.X; [Tooltip("Multiplied on the X value when it's set")] public float XMultiplier = 1; [Tooltip("Where should the Y value be set")] public VectorFields SetYOn = VectorFields.X; [Tooltip("Multiplied on the Y value when it's set")] public float YMultiplier = 1; public Vector3 Convert(Vector2 convertFrom) { float x = 0; float y = 0; float z = 0; Dictionary<VectorFields, Action<float>> setActions = new Dictionary<VectorFields, Action<float>>() { { VectorFields.X, val => x = val }, { VectorFields.Y, val => y = val }, { VectorFields.Z, val => z = val }, }; setActions[SetXOn](convertFrom.x * XMultiplier); setActions[SetYOn](convertFrom.y * YMultiplier); return new Vector3(x, y, z); } } public enum VectorFields { X, Y, Z, } } ```
170c8fa8-ef2d-483a-9f5d-45422bb6ea13
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.13-rc1")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Add Employee Standard Hours endpoints
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.13")] [assembly: AssemblyFileVersion("1.0.0.0")] ```
a413aa7c-ee9a-4f79-86e8-6e2d779816a2
{ "language": "C#" }
```c# @{ ViewBag.Title = "Home Page"; } <div class="col-md-5"> <h1> Vendo 5.0 </h1> <p class="lead">The Future of Vending Machines</p> <p class="text-justify"> Vendo 5.0 is among the first digitally integrated vending machines of the 21st century. It's so great, that we skipped the first four versions and went straight to 5. With Vendo 5.0, you have the ability to access our machines through your smartphone or P.C. Create an account with us and explore the Vendo lifestyle. You'll have access to each the machines in your area and the ability to control what the machine grabs for you. Whether it's candy, chips or soda, Vendo 5.0 can satisfy your nourishment. So, sign up today and live life the Vendo way! </p> </div> <img src="~/img/Vendo.png" class="center-block" /> <div class="row"> <div class="col-md-10 col-md-offset-1"> </div> </div> </div> ``` Add code to allow vendo img to show on Azure
```c# @{ ViewBag.Title = "Home Page"; } <div class="col-md-5"> <h1> Vendo 5.0 </h1> <p class="lead">The Future of Vending Machines</p> <p class="text-justify"> Vendo 5.0 is among the first digitally integrated vending machines of the 21st century. It's so great, that we skipped the first four versions and went straight to 5. With Vendo 5.0, you have the ability to access our machines through your smartphone or P.C. Create an account with us and explore the Vendo lifestyle. You'll have access to each the machines in your area and the ability to control what the machine grabs for you. Whether it's candy, chips or soda, Vendo 5.0 can satisfy your nourishment. So, sign up today and live life the Vendo way! </p> </div> <img src="~/img/Vendo.png" class="center-block" /> <img id="vendo" src='<%=ResolveUrl("~/img/Vendo.png") %>' /> <div class="row"> <div class="col-md-10 col-md-offset-1"> </div> </div> ```
79810ebf-2d8c-456a-853a-81e445ec13d9
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.6.0.0")] [assembly: AssemblyFileVersion("0.6.0.0")] ``` Increase project version number to 0.7.0
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.0.0")] ```
2f3162a2-8fe3-41ea-b783-e4f1a18fbb72
{ "language": "C#" }
```c# using System; using LinqToTTreeInterfacesLib; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; } public IValue InitialValue { get; set; } public bool Declare { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } } ``` Add the ability to have a simple variable declared inline.
```c# using System; using LinqToTTreeInterfacesLib; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; } public IValue InitialValue { get; set; } /// <summary> /// Get/Set if this variable needs to be declared. /// </summary> public bool Declare { get; set; } } } ```
f1de2da5-d9f1-495c-9af4-6e94b0f50085
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace MvcSandbox { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } public static void Main(string[] args) { var host = CreateWebHostBuilder(args) .Build(); host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureLogging(factory => { factory .AddConsole() .AddDebug(); }) .UseIISIntegration() .UseKestrel() .UseStartup<Startup>(); } } ``` Use latest compat version in MvcSandbox
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace MvcSandbox { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } public static void Main(string[] args) { var host = CreateWebHostBuilder(args) .Build(); host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureLogging(factory => { factory .AddConsole() .AddDebug(); }) .UseIISIntegration() .UseKestrel() .UseStartup<Startup>(); } } ```
538163b9-7b0a-4ca4-bc4b-8913423dfb09
{ "language": "C#" }
```c# // ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using NodaTime; using Squidex.Domain.Apps.Core.Contents; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Entities.Contents { public sealed class ScheduleJob { public Guid Id { get; } public Status Status { get; } public RefToken ScheduledBy { get; } public Instant DueTime { get; } public ScheduleJob(Guid id, Status status, RefToken by, Instant due) { Id = id; ScheduledBy = by; Status = status; DueTime = due; } public static ScheduleJob Build(Status status, RefToken by, Instant due) { return new ScheduleJob(Guid.NewGuid(), status, by, due); } } } ``` Fix deserialization of scheduled job.
```c# // ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using NodaTime; using Squidex.Domain.Apps.Core.Contents; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Entities.Contents { public sealed class ScheduleJob { public Guid Id { get; } public Status Status { get; } public RefToken ScheduledBy { get; } public Instant DueTime { get; } public ScheduleJob(Guid id, Status status, RefToken scheduledBy, Instant due) { Id = id; ScheduledBy = scheduledBy; Status = status; DueTime = due; } public static ScheduleJob Build(Status status, RefToken by, Instant due) { return new ScheduleJob(Guid.NewGuid(), status, by, due); } } } ```
9971b18e-6039-4018-ba30-29d15d0f2097
{ "language": "C#" }
```c# using System.Linq; using Diploms.Dto; using Microsoft.AspNetCore.Mvc; namespace Diploms.WebUI { public static class ControllerExtensions { public static OperationResult GetErrors(this Controller controller, object model) { var result = new OperationResult(); if (model == null) { result.Errors.Add("Ошибка ввода данных"); } result.Errors.AddRange(controller.ModelState.Values.SelectMany(v => v.Errors .Where(b => !string.IsNullOrEmpty(b.ErrorMessage)) .Select(b => b.ErrorMessage))); return result; } } }``` Add special http method to return unprocessable entities
```c# using System.Linq; using Diploms.Dto; using Microsoft.AspNetCore.Mvc; namespace Diploms.WebUI { public static class ControllerExtensions { public static OperationResult GetErrors(this Controller controller, object model) { var result = new OperationResult(); if (model == null) { result.Errors.Add("Ошибка ввода данных"); } result.Errors.AddRange(controller.ModelState.Values.SelectMany(v => v.Errors .Where(b => !string.IsNullOrEmpty(b.ErrorMessage)) .Select(b => b.ErrorMessage))); return result; } public static IActionResult Unprocessable(this Controller controller, object value) { return controller.StatusCode(422, value); } } }```
ba333ca7-2335-4d97-aa16-df07eb85dde0
{ "language": "C#" }
```c# using System.Linq; using System.Text; using System.Threading.Tasks; using HipChatConnect.Controllers.Listeners.Github.Models; using HipChatConnect.Controllers.Listeners.TeamCity; namespace HipChatConnect.Controllers.Listeners.Github { public class GithubAggregator { private IHipChatRoom Room { get; } public GithubAggregator(IHipChatRoom room) { Room = room; } public async Task Handle(GithubPushNotification notification) { await SendTeamsInformationAsync(notification); } private async Task SendTeamsInformationAsync(GithubPushNotification notification) { var githubModel = notification.GithubModel; (var title, var text) = BuildMessage(githubModel); var cardData = new SuccessfulTeamsActivityCardData { Title = title, Text = text }; await Room.SendTeamsActivityCardAsync(cardData); } private static (string Title, string Text) BuildMessage(GithubModel model) { var branch = model.Ref.Replace("refs/heads/", ""); var authorNames = model.Commits.Select(c => c.Author.Name).Distinct(); var title = $"**{string.Join(", ", authorNames)}** committed on [{branch}]({model.Repository.HtmlUrl + "/tree/" + branch})"; var stringBuilder = new StringBuilder(); foreach (var commit in model.Commits) { stringBuilder.Append($@"* {commit.Message} [{commit.Id.Substring(0, 11)}]({commit.Url})"); } return (title, stringBuilder.ToString()); } } }``` Fix some formatting for Teams
```c# using System.Linq; using System.Text; using System.Threading.Tasks; using HipChatConnect.Controllers.Listeners.Github.Models; using HipChatConnect.Controllers.Listeners.TeamCity; namespace HipChatConnect.Controllers.Listeners.Github { public class GithubAggregator { private IHipChatRoom Room { get; } public GithubAggregator(IHipChatRoom room) { Room = room; } public async Task Handle(GithubPushNotification notification) { await SendTeamsInformationAsync(notification); } private async Task SendTeamsInformationAsync(GithubPushNotification notification) { var githubModel = notification.GithubModel; (var title, var text) = BuildMessage(githubModel); var cardData = new SuccessfulTeamsActivityCardData { Title = title, Text = text }; await Room.SendTeamsActivityCardAsync(cardData); } private static (string Title, string Text) BuildMessage(GithubModel model) { var branch = model.Ref.Replace("refs/heads/", ""); var authorNames = model.Commits.Select(c => c.Author.Name).Distinct().ToList(); var title = $"{string.Join(", ", authorNames)} committed on {branch}"; var stringBuilder = new StringBuilder(); stringBuilder.AppendLine( $"**{string.Join(", ", authorNames)}** committed on [{branch}]({model.Repository.HtmlUrl + "/tree/" + branch})"); foreach (var commit in model.Commits) { stringBuilder.AppendLine($@"* {commit.Message} [{commit.Id.Substring(0, 11)}]({commit.Url})"); stringBuilder.AppendLine(); } return (title, stringBuilder.ToString()); } } }```
dc99fbbd-e980-40cf-a31d-fa2c711bd001
{ "language": "C#" }
```c# using System.Reflection; using Microsoft.Xna.Framework; using CocosDenshion; using CocosSharp; namespace Chess_Demo { class AppDelegate : CCApplicationDelegate { static CCWindow sharedWindow; public static CCWindow SharedWindow { get { return sharedWindow; } } public static CCSize DefaultResolution; public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow) { application.ContentRootDirectory = "assets"; sharedWindow = mainWindow; DefaultResolution = new CCSize( application.MainWindow.WindowSizeInPixels.Width, application.MainWindow.WindowSizeInPixels.Height); CCScene scene = new CCScene(sharedWindow); sharedWindow.RunWithScene(scene); } public override void ApplicationDidEnterBackground(CCApplication application) { application.Paused = true; } public override void ApplicationWillEnterForeground(CCApplication application) { application.Paused = false; } } } ``` Add Layer to scene. Currently breaking on asset load
```c# using System.Reflection; using Microsoft.Xna.Framework; using CocosDenshion; using CocosSharp; namespace Chess_Demo { class AppDelegate : CCApplicationDelegate { static CCWindow sharedWindow; public static CCWindow SharedWindow { get { return sharedWindow; } } public static CCSize DefaultResolution; public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow) { application.ContentRootDirectory = "assets"; sharedWindow = mainWindow; DefaultResolution = new CCSize( application.MainWindow.WindowSizeInPixels.Width, application.MainWindow.WindowSizeInPixels.Height); CCScene scene = new CCScene(sharedWindow); scene.AddChild(new ChessLayer()); sharedWindow.RunWithScene(scene); } public override void ApplicationDidEnterBackground(CCApplication application) { application.Paused = true; } public override void ApplicationWillEnterForeground(CCApplication application) { application.Paused = false; } } } ```
ad0b1650-5e03-4284-8c4a-9a423eec730c
{ "language": "C#" }
```c# using Medallion.OData.Sql; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Medallion.OData.Samples.Web.Models { public class Provider : DatabaseProvider { protected override string GetSqlTypeName(Trees.ODataExpressionType oDataType) { throw new NotImplementedException(); } protected override System.Collections.IEnumerable Execute(string sql, IReadOnlyList<Parameter> parameters, Type resultType) { throw new NotImplementedException(); } protected override int ExecuteCount(string sql, IReadOnlyList<Parameter> parameters) { throw new NotImplementedException(); } } }``` Build fix after namespace adjustment
```c# using Medallion.OData.Service.Sql; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Medallion.OData.Samples.Web.Models { public class Provider : DatabaseProvider { protected override string GetSqlTypeName(Trees.ODataExpressionType oDataType) { throw new NotImplementedException(); } protected override System.Collections.IEnumerable Execute(string sql, IReadOnlyList<Parameter> parameters, Type resultType) { throw new NotImplementedException(); } protected override int ExecuteCount(string sql, IReadOnlyList<Parameter> parameters) { throw new NotImplementedException(); } } }```
10c48f98-c2fc-4600-b57e-5901c971a39a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace MemoryGames { public class CardRandomPosition { private List<CardFace> gameCard = new List<CardFace>(); private string[] cardName = new string[8];//here will be the name of the card private Random randomGenerator = new Random(); public static void FillMatrix() { } internal static CardFace[,] GetRandomCardFace() { throw new NotImplementedException(); } } } ``` Add random position of card
```c# using System; using System.Collections.Generic; using System.Linq; namespace MemoryGames { public class CardRandomPosition { public static CardFace[,] GetRandomCardFace(int dimentionZero, int dimentionOne) { const int pair = 2; const int pairCount = 9; CardFace[,] cardFace = new CardFace[dimentionZero, dimentionOne]; Random randomGenerator = new Random(); List<CardFace> gameCard = new List<CardFace>(); int allCard = dimentionZero * dimentionOne; int currentGameCardPair = allCard / pair; string[] cardName = new string[pairCount] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; for (int element = 0, j = 0; element < allCard; element++, j++) { if (j == currentGameCardPair) { j = 0; } gameCard.Add(new CardFace(cardName[j])); } for (int row = 0; row < dimentionZero; row++) { for (int col = 0; col < dimentionOne; col++) { int randomElement = randomGenerator.Next(0, gameCard.Count); cardFace[row, col] = gameCard[randomElement]; gameCard.RemoveAt(randomElement); } } return cardFace; } } } ```
2f1c7afc-a7de-4d65-972b-6fc273e87c00
{ "language": "C#" }
```c# /* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using Microsoft.NodejsTools.Analysis; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AnalysisTests { [TestClass] internal class SerializedAnalysisTests : AnalysisTests { internal override ModuleAnalysis ProcessText(string text) { return SerializationTests.RoundTrip(ProcessOneText(text)); } } } ``` Test needs to be public
```c# /* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using Microsoft.NodejsTools.Analysis; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AnalysisTests { [TestClass] public class SerializedAnalysisTests : AnalysisTests { internal override ModuleAnalysis ProcessText(string text) { return SerializationTests.RoundTrip(ProcessOneText(text)); } } } ```
8b34e60a-103b-4e6d-80fe-97a1e67a03ec
{ "language": "C#" }
```c# using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class WeaponsController : ApiController { public WeaponsController(Database db) : base(db) { // Nothing to do here } [HttpGet] public async Task<IEnumerable<dynamic>> Get() { // GET: api/weapons return await db .Weapons .Select(_ => new { _.Id, _.OpticSerial, _.OpticType, _.Serial, _.StockNumber, _.Type, _.UnitId }) .ToListAsync(); } [HttpPost] public async Task<IActionResult> Post([FromBody]Weapon weapon) { await db.Weapons.AddAsync(weapon); await db.SaveChangesAsync(); return Ok(); } [HttpDelete] public async Task<IActionResult> Delete(int id) { var weapon = await db.Weapons.FindAsync(id); db.Weapons.Remove(weapon); await db.SaveChangesAsync(); return Ok(); } } }``` Allow filtering weapons by unit
```c# using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class WeaponsController : ApiController { public WeaponsController(Database db) : base(db) { // Nothing to do here } [HttpGet] public async Task<IActionResult> Get(int? unit) { // GET: api/weapons return Ok( await db .Weapons .Where(weapon => !unit.HasValue || weapon.UnitId == unit) .Select(_ => new { _.Id, _.OpticSerial, _.OpticType, _.Serial, _.StockNumber, _.Type, _.UnitId }) .ToListAsync()); } [HttpPost] public async Task<IActionResult> Post([FromBody]Weapon weapon) { await db.Weapons.AddAsync(weapon); await db.SaveChangesAsync(); return Ok(); } [HttpDelete] public async Task<IActionResult> Delete(int id) { var weapon = await db.Weapons.FindAsync(id); db.Weapons.Remove(weapon); await db.SaveChangesAsync(); return Ok(); } } }```
c7397809-e94e-4bbb-a180-e33cf5fddd9f
{ "language": "C#" }
```c# using System.Threading.Tasks; using Auth0.AuthenticationApi; using Auth0.AuthenticationApi.Models; using Microsoft.Extensions.Configuration; namespace Auth0.Tests.Shared { public class TestBase { private readonly IConfigurationRoot _config; public TestBase() { _config = new ConfigurationBuilder() .AddJsonFile("client-secrets.json", true) .AddEnvironmentVariables() .Build(); } protected async Task<string> GenerateManagementApiToken() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); // Get the access token var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest { ClientId = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_SECRET"), Audience = GetVariable("AUTH0_MANAGEMENT_API_AUDIENCE") }); return token.AccessToken; } protected string GetVariable(string variableName) { return _config[variableName]; } } }``` Check configuration values are set in tests
```c# using System; using System.Threading.Tasks; using Auth0.AuthenticationApi; using Auth0.AuthenticationApi.Models; using Microsoft.Extensions.Configuration; namespace Auth0.Tests.Shared { public class TestBase { private readonly IConfigurationRoot _config; public TestBase() { _config = new ConfigurationBuilder() .AddJsonFile("client-secrets.json", true) .AddEnvironmentVariables() .Build(); } protected async Task<string> GenerateManagementApiToken() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); // Get the access token var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest { ClientId = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_SECRET"), Audience = GetVariable("AUTH0_MANAGEMENT_API_AUDIENCE") }); return token.AccessToken; } protected string GetVariable(string variableName) { var value = _config[variableName]; if (String.IsNullOrEmpty(value)) throw new ArgumentOutOfRangeException($"Configuration value '{variableName}' has not been set."); return value; } } }```
4cb75909-d278-4d8a-b12b-dcc62ec284f2
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the program class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConfigurationConsole { using System.Runtime.Loader; using System.Threading.Tasks; using StartupConsole.Application; class Program { public static async Task Main(string[] args) { AssemblyLoadContext.Default.Resolving += (context, name) => { if (name.Name.EndsWith(".resources")) { return null; } return null; }; await new ConsoleShell().BootstrapAsync(args); } } } ``` Comment out the resource not found fix for .NET Core
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the program class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConfigurationConsole { using System.Runtime.Loader; using System.Threading.Tasks; using StartupConsole.Application; class Program { public static async Task Main(string[] args) { //AssemblyLoadContext.Default.Resolving += (context, name) => // { // if (name.Name.EndsWith(".resources")) // { // return null; // } // return null; // }; await new ConsoleShell().BootstrapAsync(args); } } } ```
14e6f43f-341c-4bd5-ba39-248363362a2f
{ "language": "C#" }
```c# using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height); } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }``` Fix issue where ratio was always returning "1"
```c# using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height; } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }```
f78b5ea8-9966-4adf-8194-ebf00b5f6fe3
{ "language": "C#" }
```c# using System; using TeaCommerce.Api.Dependency; using TeaCommerce.Api.Infrastructure.Caching; using Umbraco.Core; using Umbraco.Core.Cache; namespace TeaCommerce.Umbraco.Application.Caching { [SuppressDependency("TeaCommerce.Api.Infrastructure.Caching.ICacheService", "TeaCommerce.Api")] public class UmbracoRuntimeCacheService : ICacheService { private IRuntimeCacheProvider _runtimeCache; public UmbracoRuntimeCacheService() : this(ApplicationContext.Current.ApplicationCache.RuntimeCache) { } public UmbracoRuntimeCacheService(IRuntimeCacheProvider runtimeCache) { _runtimeCache = runtimeCache; } public T GetCacheValue<T>(string cacheKey) where T : class { return (T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}"); } public void Invalidate(string cacheKey) { _runtimeCache.ClearCacheItem($"TeaCommerce_{cacheKey}"); } public void SetCacheValue(string cacheKey, object cacheValue) { _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue); } public void SetCacheValue(string cacheKey, object cacheValue, TimeSpan cacheDuration) { _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue, cacheDuration); } } }``` Enable sliding expiration by default as that is what the Tea Commerce cache does
```c# using System; using TeaCommerce.Api.Dependency; using TeaCommerce.Api.Infrastructure.Caching; using Umbraco.Core; using Umbraco.Core.Cache; namespace TeaCommerce.Umbraco.Application.Caching { [SuppressDependency("TeaCommerce.Api.Infrastructure.Caching.ICacheService", "TeaCommerce.Api")] public class UmbracoRuntimeCacheService : ICacheService { private IRuntimeCacheProvider _runtimeCache; public UmbracoRuntimeCacheService() : this(ApplicationContext.Current.ApplicationCache.RuntimeCache) { } public UmbracoRuntimeCacheService(IRuntimeCacheProvider runtimeCache) { _runtimeCache = runtimeCache; } public T GetCacheValue<T>(string cacheKey) where T : class { return (T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}"); } public void Invalidate(string cacheKey) { _runtimeCache.ClearCacheItem($"TeaCommerce_{cacheKey}"); } public void SetCacheValue(string cacheKey, object cacheValue) { _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue); } public void SetCacheValue(string cacheKey, object cacheValue, TimeSpan cacheDuration) { _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue, cacheDuration, true); } } }```
44bc58ff-4089-407e-baa4-0ca5502232b9
{ "language": "C#" }
```c# public class StudentControllerTests { [SetUp] public void Setup() { _fixture = new DatabaseFixture(); _controller = new StudentController(new StudentRepository(_fixture.Context)); } [Test] public void IndexAction_ShowsAllStudentsOrderedByName() { var expectedStudents = new List<Student> { new Student("Joe", "Bloggs"), new Student("Jane", "Smith") }; expectedStudents.ForEach(_fixture.SeedContext.Students.Add) _fixture.SeedContext.SaveChanges(); List<StudentViewModel> viewModel; _controller.Index() .ShouldRenderDefaultView() .WithModel<List<StudentViewModel>>(vm => viewModel = vm); viewModel.Select(s => s.Name).ShouldBe( _existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName)) } private StudentController _controller; private DatabaseFixture _fixture; }``` Fix a missing semicolon in an example
```c# public class StudentControllerTests { [SetUp] public void Setup() { _fixture = new DatabaseFixture(); _controller = new StudentController(new StudentRepository(_fixture.Context)); } [Test] public void IndexAction_ShowsAllStudentsOrderedByName() { var expectedStudents = new List<Student> { new Student("Joe", "Bloggs"), new Student("Jane", "Smith") }; expectedStudents.ForEach(_fixture.SeedContext.Students.Add) _fixture.SeedContext.SaveChanges(); List<StudentViewModel> viewModel; _controller.Index() .ShouldRenderDefaultView() .WithModel<List<StudentViewModel>>(vm => viewModel = vm); viewModel.Select(s => s.Name).ShouldBe( _existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName)); } private StudentController _controller; private DatabaseFixture _fixture; }```
98a02eea-89b2-4615-b397-133c919b98dc
{ "language": "C#" }
```c# using UnityEditor; using UnityEngine; namespace GoogleMobileAds.Editor { [InitializeOnLoad] [CustomEditor(typeof(GoogleMobileAdsSettings))] public class GoogleMobileAdsSettingsEditor : UnityEditor.Editor { [MenuItem("Assets/Google Mobile Ads/Settings...")] public static void OpenInspector() { Selection.activeObject = GoogleMobileAdsSettings.Instance; if (GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit) { EditorGUILayout.HelpBox( "Delays app measurement until you explicitly initialize the Mobile Ads SDK or load an ad.", MessageType.Info); } EditorGUI.indentLevel--; EditorGUILayout.Separator(); if (GUI.changed) { OnSettingsChanged(); } } private void OnSettingsChanged() { EditorUtility.SetDirty((GoogleMobileAdsSettings) target); GoogleMobileAdsSettings.Instance.WriteSettingsToFile(); } } } ``` Fix erroneous removal of code
```c# using UnityEditor; using UnityEngine; namespace GoogleMobileAds.Editor { [InitializeOnLoad] [CustomEditor(typeof(GoogleMobileAdsSettings))] public class GoogleMobileAdsSettingsEditor : UnityEditor.Editor { [MenuItem("Assets/Google Mobile Ads/Settings...")] public static void OpenInspector() { Selection.activeObject = GoogleMobileAdsSettings.Instance; } public override void OnInspectorGUI() { EditorGUILayout.LabelField("Google Mobile Ads App ID", EditorStyles.boldLabel); EditorGUI.indentLevel++; GoogleMobileAdsSettings.Instance.GoogleMobileAdsAndroidAppId = EditorGUILayout.TextField("Android", GoogleMobileAdsSettings.Instance.GoogleMobileAdsAndroidAppId); GoogleMobileAdsSettings.Instance.GoogleMobileAdsIOSAppId = EditorGUILayout.TextField("iOS", GoogleMobileAdsSettings.Instance.GoogleMobileAdsIOSAppId); EditorGUILayout.HelpBox( "Google Mobile Ads App ID will look similar to this sample ID: ca-app-pub-3940256099942544~3347511713", MessageType.Info); EditorGUI.indentLevel--; EditorGUILayout.Separator(); EditorGUILayout.LabelField("AdMob-specific settings", EditorStyles.boldLabel); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit = EditorGUILayout.Toggle(new GUIContent("Delay app measurement"), GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit); if (GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit) { EditorGUILayout.HelpBox( "Delays app measurement until you explicitly initialize the Mobile Ads SDK or load an ad.", MessageType.Info); } EditorGUI.indentLevel--; EditorGUILayout.Separator(); if (GUI.changed) { OnSettingsChanged(); } } private void OnSettingsChanged() { EditorUtility.SetDirty((GoogleMobileAdsSettings) target); GoogleMobileAdsSettings.Instance.WriteSettingsToFile(); } } } ```
3b68337d-a710-42f3-bc7c-8356ae80077f
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Text; namespace Novell.Directory.Ldap { internal static partial class ExtensionMethods { /// <summary> /// Is the given collection null, or Empty (0 elements)? /// </summary> internal static bool IsEmpty<T>(this IReadOnlyCollection<T> coll) => coll == null || coll.Count == 0; /// <summary> /// Is the given collection not null, and has at least 1 element? /// </summary> /// <typeparam name="T"></typeparam> /// <param name="coll"></param> /// <returns></returns> internal static bool IsNotEmpty<T>(this IReadOnlyCollection<T> coll) => !IsEmpty(coll); /// <summary> /// Shortcut for Encoding.UTF8.GetBytes /// </summary> internal static byte[] ToUtf8Bytes(this string input) => Encoding.UTF8.GetBytes(input); } } ``` Add more string extension methods for common operations
```c# using System; using System.Collections.Generic; using System.Text; namespace Novell.Directory.Ldap { internal static partial class ExtensionMethods { /// <summary> /// Shortcut for <see cref="string.IsNullOrEmpty"/> /// </summary> internal static bool IsEmpty(this string input) => string.IsNullOrEmpty(input); /// <summary> /// Shortcut for negative <see cref="string.IsNullOrEmpty"/> /// </summary> internal static bool IsNotEmpty(this string input) => !IsEmpty(input); /// <summary> /// Is the given collection null, or Empty (0 elements)? /// </summary> internal static bool IsEmpty<T>(this IReadOnlyCollection<T> coll) => coll == null || coll.Count == 0; /// <summary> /// Is the given collection not null, and has at least 1 element? /// </summary> /// <typeparam name="T"></typeparam> /// <param name="coll"></param> /// <returns></returns> internal static bool IsNotEmpty<T>(this IReadOnlyCollection<T> coll) => !IsEmpty(coll); /// <summary> /// Shortcut for <see cref="UTF8Encoding.GetBytes"/> /// </summary> internal static byte[] ToUtf8Bytes(this string input) => Encoding.UTF8.GetBytes(input); /// <summary> /// Shortcut for <see cref="UTF8Encoding.GetString"/> /// Will return an empty string if <paramref name="input"/> is null or empty. /// </summary> internal static string FromUtf8Bytes(this byte[] input) => input.IsNotEmpty() ? Encoding.UTF8.GetString(input) : string.Empty; /// <summary> /// Compare two strings using <see cref="StringComparison.Ordinal"/> /// </summary> internal static bool EqualsOrdinal(this string input, string other) => string.Equals(input, other, StringComparison.Ordinal); /// <summary> /// Compare two strings using <see cref="StringComparison.OrdinalIgnoreCase"/> /// </summary> internal static bool EqualsOrdinalCI(this string input, string other) => string.Equals(input, other, StringComparison.OrdinalIgnoreCase); } } ```
99028c06-4f5c-4f0c-9046-2578d303da1e
{ "language": "C#" }
```c# // TodoItem.cs // using System; using System.Runtime.CompilerServices; namespace Todo { [Imported] [IgnoreNamespace] [ScriptName("Object")] internal sealed class TodoItem { public bool Completed; [ScriptName("id")] public string ID; public string Title; } } ``` Update todo sample for latest metadata changes
```c# // TodoItem.cs // using System; using System.Runtime.CompilerServices; namespace Todo { [ScriptImport] [ScriptIgnoreNamespace] [ScriptName("Object")] internal sealed class TodoItem { public bool Completed; [ScriptName("id")] public string ID; public string Title; } } ```
f98daa4a-a474-439e-9447-9928bab39dff
{ "language": "C#" }
```c# using System.Collections.Generic; using BugsnagUnity.Payload; using UnityEngine; namespace BugsnagUnity { static class DictionaryExtensions { internal static void PopulateDictionaryFromAndroidData(this IDictionary<string, object> dictionary, AndroidJavaObject source) { using (var set = source.Call<AndroidJavaObject>("entrySet")) using (var iterator = set.Call<AndroidJavaObject>("iterator")) { while (iterator.Call<bool>("hasNext")) { using (var mapEntry = iterator.Call<AndroidJavaObject>("next")) { var key = mapEntry.Call<string>("getKey"); using (var value = mapEntry.Call<AndroidJavaObject>("getValue")) { if (value != null) { using (var @class = value.Call<AndroidJavaObject>("getClass")) { if (@class.Call<bool>("isArray")) { using (var arrays = new AndroidJavaClass("java.util.Arrays")) { dictionary.AddToPayload(key, arrays.CallStatic<string>("toString", value)); } } else { dictionary.AddToPayload(key, value.Call<string>("toString")); } } } } } } } } } } ``` Use a more compatible method call
```c# using System; using System.Collections.Generic; using BugsnagUnity.Payload; using UnityEngine; namespace BugsnagUnity { static class DictionaryExtensions { private static IntPtr Arrays { get; } = AndroidJNI.FindClass("java/util/Arrays"); private static IntPtr ToStringMethod { get; } = AndroidJNIHelper.GetMethodID(Arrays, "toString", "([Ljava/lang/Object;)Ljava/lang/String;", true); internal static void PopulateDictionaryFromAndroidData(this IDictionary<string, object> dictionary, AndroidJavaObject source) { using (var set = source.Call<AndroidJavaObject>("entrySet")) using (var iterator = set.Call<AndroidJavaObject>("iterator")) { while (iterator.Call<bool>("hasNext")) { using (var mapEntry = iterator.Call<AndroidJavaObject>("next")) { var key = mapEntry.Call<string>("getKey"); using (var value = mapEntry.Call<AndroidJavaObject>("getValue")) { if (value != null) { using (var @class = value.Call<AndroidJavaObject>("getClass")) { if (@class.Call<bool>("isArray")) { var args = AndroidJNIHelper.CreateJNIArgArray(new[] {value}); var formattedValue = AndroidJNI.CallStaticStringMethod(Arrays, ToStringMethod, args); dictionary.AddToPayload(key, formattedValue); } else { dictionary.AddToPayload(key, value.Call<string>("toString")); } } } } } } } } } } ```
3c52d470-51de-4cd5-8931-623ef002dd64
{ "language": "C#" }
```c# namespace SIM.Tool.Windows.MainWindowComponents { using System; using System.IO; using System.Windows; using Sitecore.Diagnostics.Base; using JetBrains.Annotations; using SIM.Core; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; [UsedImplicitly] public class CreateSupportPatchButton : IMainWindowButton { #region Public methods public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { if (instance == null) { WindowHelper.ShowMessage("Choose an instance first"); return; } var product = instance.Product; Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first."); var version = product.Version + "." + product.Update; var args = new[] { version, instance.Name, instance.WebRootPath }; var dir = Environment.ExpandEnvironmentVariables("%APPDATA%\\Sitecore\\PatchCreator"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllLines(Path.Combine(dir, "args.txt"), args); CoreApp.RunApp("iexplore", $"http://dl.sitecore.net/updater/pc/PatchCreator.application"); } #endregion } } ``` Add properties to patch creator button
```c# namespace SIM.Tool.Windows.MainWindowComponents { using System; using System.IO; using System.Windows; using Sitecore.Diagnostics.Base; using JetBrains.Annotations; using SIM.Core; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; [UsedImplicitly] public class CreateSupportPatchButton : IMainWindowButton { #region Public methods private string AppArgsFilePath { get; } private string AppUrl { get; } public CreateSupportPatchButton(string appArgsFilePath, string appUrl) { AppArgsFilePath = appArgsFilePath; AppUrl = appUrl; } public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { if (instance == null) { WindowHelper.ShowMessage("Choose an instance first"); return; } var product = instance.Product; Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first."); var version = product.Version + "." + product.Update; var args = new[] { version, instance.Name, instance.WebRootPath }; var dir = Environment.ExpandEnvironmentVariables(AppArgsFilePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllLines(Path.Combine(dir, "args.txt"), args); CoreApp.RunApp("iexplore", AppUrl); } #endregion } } ```
b8f75df8-6ca7-48a6-93ce-0a00a0411b74
{ "language": "C#" }
```c# using System; using Faithlife.Build; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { build.AddDotNetTargets( new DotNetBuildSettings { DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("faithlifebuildbot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("Faithlife Build Bot", "faithlifebuildbot@users.noreply.github.com"), SourceCodeUrl = "https://github.com/Faithlife/RepoName/tree/master/src", }, }); }); } ``` Set default build target to build.
```c# using System; using Faithlife.Build; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { build.AddDotNetTargets( new DotNetBuildSettings { DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("faithlifebuildbot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("Faithlife Build Bot", "faithlifebuildbot@users.noreply.github.com"), SourceCodeUrl = "https://github.com/Faithlife/RepoName/tree/master/src", }, }); build.Target("default") .DependsOn("build"); }); } ```
713d88ad-9262-4509-9267-8c69e784952b
{ "language": "C#" }
```c# using System; using System.Linq; using ExactTarget.TriggeredEmail.ExactTargetApi; namespace ExactTarget.TriggeredEmail.Core { public class ExactTargetResultChecker { public static void CheckResult(Result result) { if (result == null) { throw new Exception("Received an unexpected null result from ExactTarget"); } if (result.StatusCode.Equals("OK", StringComparison.InvariantCultureIgnoreCase)) { return; } var triggeredResult = result as TriggeredSendCreateResult; var subscriberFailures = triggeredResult == null ? Enumerable.Empty<string>() : triggeredResult.SubscriberFailures.Select(f => " ErrorCode:" + f.ErrorCode + " ErrorDescription:" + f.ErrorDescription); throw new Exception(string.Format("ExactTarget response indicates failure. StatusCode:{0} StatusMessage:{1} SubscriberFailures:{2}", result.StatusCode, result.StatusMessage, string.Join("|", subscriberFailures))); } } }``` Fix result checker if no subscriber errors in response
```c# using System; using System.Linq; using ExactTarget.TriggeredEmail.ExactTargetApi; namespace ExactTarget.TriggeredEmail.Core { public class ExactTargetResultChecker { public static void CheckResult(Result result) { if (result == null) { throw new Exception("Received an unexpected null result from ExactTarget"); } if (result.StatusCode.Equals("OK", StringComparison.InvariantCultureIgnoreCase)) { return; } var triggeredResult = result as TriggeredSendCreateResult; var subscriberFailures = triggeredResult == null || triggeredResult.SubscriberFailures == null ? Enumerable.Empty<string>() : triggeredResult.SubscriberFailures.Select(f => " ErrorCode:" + f.ErrorCode + " ErrorDescription:" + f.ErrorDescription); throw new Exception(string.Format("ExactTarget response indicates failure. StatusCode:{0} StatusMessage:{1} SubscriberFailures:{2}", result.StatusCode, result.StatusMessage, string.Join("|", subscriberFailures))); } } }```
49350a1b-ba83-43ac-860d-edee160cf986
{ "language": "C#" }
```c# namespace EfMigrationsBug.Migrations { using System; using System.Data.Entity.Migrations; public partial class ChangePkType : DbMigration { public override void Up() { DropPrimaryKey("dbo.Foos"); AlterColumn("dbo.Foos", "ID", c => c.Int(nullable: false, identity: true)); AddPrimaryKey("dbo.Foos", "ID"); } public override void Down() { DropPrimaryKey("dbo.Foos"); AlterColumn("dbo.Foos", "ID", c => c.String(nullable: false, maxLength: 5)); AddPrimaryKey("dbo.Foos", "ID"); } } } ``` Modify the migration so it rebuilds the table.
```c# namespace EfMigrationsBug.Migrations { using System; using System.Data.Entity.Migrations; public partial class ChangePkType : DbMigration { public override void Up() { DropTable("dbo.Foos"); CreateTable( "dbo.Foos", c => new { ID = c.Int(nullable: false, identity: true), }) .PrimaryKey(t => t.ID); } public override void Down() { DropTable("dbo.Foos"); CreateTable( "dbo.Foos", c => new { ID = c.String(nullable: false, maxLength: 5), }) .PrimaryKey(t => t.ID); } } } ```
3a5713db-d532-4bee-81e3-3000f41e01db
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Aurio.Streams { public class MemoryWriterStream : MemorySourceStream, IAudioWriterStream { public MemoryWriterStream(MemoryStream target, AudioProperties properties) : base(target, properties) { } public void Write(byte[] buffer, int offset, int count) { // Default stream checks according to MSDN if(buffer == null) { throw new ArgumentNullException("buffer must not be null"); } if(!source.CanWrite) { throw new NotSupportedException("target stream is not writable"); } if(buffer.Length - offset < count) { throw new ArgumentException("not enough remaining bytes or count too large"); } if(offset < 0 || count < 0) { throw new ArgumentOutOfRangeException("offset and count must not be negative"); } // Check block alignment if(count % SampleBlockSize != 0) { throw new ArgumentException("count must be a multiple of the sample block size"); } source.Write(buffer, offset, count); } } } ``` Add constructor that creates memory stream internally
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Aurio.Streams { public class MemoryWriterStream : MemorySourceStream, IAudioWriterStream { public MemoryWriterStream(MemoryStream target, AudioProperties properties) : base(target, properties) { } public MemoryWriterStream(AudioProperties properties) : base(new MemoryStream(), properties) { } public void Write(byte[] buffer, int offset, int count) { // Default stream checks according to MSDN if(buffer == null) { throw new ArgumentNullException("buffer must not be null"); } if(!source.CanWrite) { throw new NotSupportedException("target stream is not writable"); } if(buffer.Length - offset < count) { throw new ArgumentException("not enough remaining bytes or count too large"); } if(offset < 0 || count < 0) { throw new ArgumentOutOfRangeException("offset and count must not be negative"); } // Check block alignment if(count % SampleBlockSize != 0) { throw new ArgumentException("count must be a multiple of the sample block size"); } source.Write(buffer, offset, count); } } } ```
9a9c7c61-9dbf-4f73-a73d-d4adb8b0eb24
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="TypeExtensions.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // <summary> // Provides extension methods for types. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot { using System; using System.Linq; using System.Reflection; /// <summary> /// Provides extension methods for types. /// </summary> public static class TypeExtensions { /// <summary> /// Retrieves an object that represents a specified property. /// </summary> /// <param name="type">The type that contains the property.</param> /// <param name="name">The name of the property.</param> /// <returns>An object that represents the specified property, or null if the property is not found.</returns> public static PropertyInfo GetRuntimeProperty(this Type type, string name) { #if NET40 var source = type.GetProperties(); #else var typeInfo = type.GetTypeInfo(); var source = typeInfo.AsType().GetRuntimeProperties(); #endif foreach (var x in source) { if (x.Name == name) return x; } return null; } } } ``` Update type extension for net40
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="TypeExtensions.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // <summary> // Provides extension methods for types. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot { using System; using System.Linq; using System.Reflection; /// <summary> /// Provides extension methods for types. /// </summary> public static class TypeExtensions { /// <summary> /// Retrieves an object that represents a specified property. /// </summary> /// <param name="type">The type that contains the property.</param> /// <param name="name">The name of the property.</param> /// <returns>An object that represents the specified property, or null if the property is not found.</returns> public static PropertyInfo GetRuntimeProperty(this Type type, string name) { #if NET40 var source = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); #else var typeInfo = type.GetTypeInfo(); var source = typeInfo.AsType().GetRuntimeProperties(); #endif foreach (var x in source) { if (x.Name == name) return x; } return null; } } } ```
f3ecdc38-189d-4bc9-9856-8517578397bf
{ "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.Platform.Linux.Native; using osu.Framework.Platform.Linux.Sdl; using osuTK; namespace osu.Framework.Platform.Linux { public class LinuxGameHost : DesktopGameHost { internal LinuxGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default, bool portableInstallation = false, bool useSdl = false) : base(gameName, bindIPC, toolkitOptions, portableInstallation, useSdl) { } protected override void SetupForRun() { base.SetupForRun(); // required for the time being to address libbass_fx.so load failures (see https://github.com/ppy/osu/issues/2852) Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); } protected override IWindow CreateWindow() => !UseSdl ? (IWindow)new LinuxGameWindow() : new Window(); protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this); public override Clipboard GetClipboard() { if (((LinuxGameWindow)Window).IsSdl) { return new SdlClipboard(); } else { return new LinuxClipboard(); } } } } ``` Use SdlClipboard on Linux when using new SDL2 backend
```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.Platform.Linux.Native; using osu.Framework.Platform.Linux.Sdl; using osuTK; namespace osu.Framework.Platform.Linux { public class LinuxGameHost : DesktopGameHost { internal LinuxGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default, bool portableInstallation = false, bool useSdl = false) : base(gameName, bindIPC, toolkitOptions, portableInstallation, useSdl) { } protected override void SetupForRun() { base.SetupForRun(); // required for the time being to address libbass_fx.so load failures (see https://github.com/ppy/osu/issues/2852) Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); } protected override IWindow CreateWindow() => !UseSdl ? (IWindow)new LinuxGameWindow() : new Window(); protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this); public override Clipboard GetClipboard() => Window is Window || (Window as LinuxGameWindow)?.IsSdl == true ? (Clipboard)new SdlClipboard() : new LinuxClipboard(); } } ```
954519bd-59f4-4d83-9d94-89877c83e919
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace mdryden.cflapi.v1.Models.Games { public class LineScore { [JsonProperty(PropertyName = "quarter")] public int Quarter { get; set; } [JsonProperty(PropertyName = "score")] public int Score { get; set; } } } ``` Change quarter type to enum to allow for "ot" as value.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace mdryden.cflapi.v1.Models.Games { public class LineScore { [JsonProperty(PropertyName = "quarter")] public Quarters Quarter { get; set; } [JsonProperty(PropertyName = "score")] public int Score { get; set; } } } ```
f55eb33b-61da-467f-add8-d777694504cb
{ "language": "C#" }
```c# using System.Linq; using EPiServer.Core; namespace Meridium.EPiServer.Migration.Support { public class SourcePage { public string TypeName { get; set; } public PropertyDataCollection Properties { get; set; } public TValue GetValue<TValue>(string propertyName, TValue @default = default(TValue)) where TValue : class { var data = Properties != null ? Properties.Get(propertyName) : null; return (data != null) ? (data.Value as TValue) : @default; } public TValue GetValueWithFallback<TValue>(params string[] properties) where TValue : class { var property = properties.SkipWhile(p => !Properties.HasValue(p)).FirstOrDefault(); return (property != null) ? GetValue<TValue>(property) : null; } } internal static class PropertyDataExtensions { public static bool HasValue(this PropertyDataCollection self, string key) { var property = self.Get(key); if (property == null) return false; return !(property.IsNull || string.IsNullOrWhiteSpace(property.ToString())); } } }``` Make GetValue method handle value types
```c# using System.Linq; using EPiServer.Core; namespace Meridium.EPiServer.Migration.Support { public class SourcePage { public string TypeName { get; set; } public PropertyDataCollection Properties { get; set; } public TValue GetValue<TValue>(string propertyName, TValue @default = default(TValue)) { var data = Properties != null ? Properties.Get(propertyName) : null; if (data != null && data.Value is TValue) return (TValue) data.Value; return @default; } public TValue GetValueWithFallback<TValue>(params string[] properties) { var property = properties.SkipWhile(p => !Properties.HasValue(p)).FirstOrDefault(); return (property != null) ? GetValue<TValue>(property) : default(TValue); } } internal static class PropertyDataExtensions { public static bool HasValue(this PropertyDataCollection self, string key) { var property = self.Get(key); if (property == null) return false; return !(property.IsNull || string.IsNullOrWhiteSpace(property.ToString())); } } }```
5f937be9-4194-4498-bc01-e361ce21378a
{ "language": "C#" }
```c# using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace Templar { public class TemplateSource : IContentSource { private readonly string global; private readonly Compiler compiler; private readonly TemplateFinder finder; public TemplateSource(string global, Compiler compiler, TemplateFinder finder) { this.global = global; this.compiler = compiler; this.finder = finder; } public string GetContent(HttpContextBase httpContext) { var templates = finder.Find(httpContext); using (var writer = new StringWriter()) { writer.WriteLine("!function() {"); writer.WriteLine(" var templates = {0}.templates = {{}};", global); var results = Compile(templates); foreach (var result in results) { writer.WriteLine(result); } writer.WriteLine("}();"); return writer.ToString(); } } private IEnumerable<string> Compile(IEnumerable<Template> templates) { return templates.AsParallel().Select(template => { string name = template.GetName(); string content = compiler.Compile(template.GetContent()); return string.Format(" templates['{0}'] = {1};", name, content); }); } } }``` Remove usage of parallelism when compiling templates (causing crash in Jurassic?).
```c# using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace Templar { public class TemplateSource : IContentSource { private readonly string global; private readonly Compiler compiler; private readonly TemplateFinder finder; public TemplateSource(string global, Compiler compiler, TemplateFinder finder) { this.global = global; this.compiler = compiler; this.finder = finder; } public string GetContent(HttpContextBase httpContext) { var templates = finder.Find(httpContext); using (var writer = new StringWriter()) { writer.WriteLine("!function() {"); writer.WriteLine(" var templates = {0}.templates = {{}};", global); var results = Compile(templates); foreach (var result in results) { writer.WriteLine(result); } writer.WriteLine("}();"); return writer.ToString(); } } private IEnumerable<string> Compile(IEnumerable<Template> templates) { return templates.Select(template => { string name = template.GetName(); string content = compiler.Compile(template.GetContent()); return string.Format(" templates['{0}'] = {1};", name, content); }); } } }```
371ba758-61b4-4237-80b7-bf8b0c1adb44
{ "language": "C#" }
```c# namespace Moya.Runner.Console { public struct OptionArgumentPair { public string Option { get; set; } public string Argument { get; set; } public static OptionArgumentPair Create(string stringFromCommandLine) { string[] optionAndArgument = stringFromCommandLine.Split('='); return new OptionArgumentPair { Option = optionAndArgument[0], Argument = optionAndArgument[1] }; } } }``` Handle optionargumentpairs with only option
```c# namespace Moya.Runner.Console { using System.Linq; public struct OptionArgumentPair { public string Option { get; set; } public string Argument { get; set; } public static OptionArgumentPair Create(string stringFromCommandLine) { string[] optionAndArgument = stringFromCommandLine.Split('='); return new OptionArgumentPair { Option = optionAndArgument.Any() ? optionAndArgument[0] : string.Empty, Argument = optionAndArgument.Count() > 1 ? optionAndArgument[1] : string.Empty }; } } }```
9c678871-7151-4e90-b62c-56a3bd1d5706
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.RealtimeMultiplayer { public enum MultiplayerUserState { Idle, Ready, WaitingForLoad, Loaded, Playing, Results, } } ``` Add missing states and xmldoc for all states' purposes
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.RealtimeMultiplayer { public enum MultiplayerUserState { /// <summary> /// The user is idle and waiting for something to happen (or watching the match but not participating). /// </summary> Idle, /// <summary> /// The user has marked themselves as ready to participate and should be considered for the next game start. /// </summary> Ready, /// <summary> /// The server is waiting for this user to finish loading. This is a reserved state, and is set by the server. /// </summary> /// <remarks> /// All users in <see cref="Ready"/> state when the game start will be transitioned to this state. /// All users in this state need to transition to <see cref="Loaded"/> before the game can start. /// </remarks> WaitingForLoad, /// <summary> /// The user's client has marked itself as loaded and ready to begin gameplay. /// </summary> Loaded, /// <summary> /// The user is currently playing in a game. This is a reserved state, and is set by the server. /// </summary> /// <remarks> /// Once there are no remaining <see cref="WaitingForLoad"/> users, all users in <see cref="Loaded"/> state will be transitioned to this state. /// At this point the game will start for all users. /// </remarks> Playing, /// <summary> /// The user has finished playing and is ready to view results. /// </summary> /// <remarks> /// Once all users transition from <see cref="Playing"/> to this state, the game will end and results will be distributed. /// All users will be transitioned to the <see cref="Results"/> state. /// </remarks> FinishedPlay, /// <summary> /// The user is currently viewing results. This is a reserved state, and is set by the server. /// </summary> Results, } } ```
9b6fc73c-657c-4cfc-83cf-09c1771b8785
{ "language": "C#" }
```c# using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; namespace CollAction.ValidationAttributes { public class RichTextRequiredAttribute : ValidationAttribute, IClientModelValidator { public void AddValidation(ClientModelValidationContext context) { context.Attributes["data-val"] = "true"; context.Attributes["data-val-richtextrequired"] = ErrorMessage ?? $"{context.ModelMetadata.DisplayName} is required"; } } }``` Add required validation for rich text components on server side
```c# using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; namespace CollAction.ValidationAttributes { public class RichTextRequiredAttribute : RequiredAttribute, IClientModelValidator { public void AddValidation(ClientModelValidationContext context) { var requiredMessage = ErrorMessage ?? $"{context.ModelMetadata.DisplayName} is required"; context.Attributes["data-val"] = "true"; context.Attributes["data-val-required"] = requiredMessage; context.Attributes["data-val-richtextrequired"] = requiredMessage; } } }```
c4631f19-7da0-4753-8806-1a68f2f88140
{ "language": "C#" }
```c# namespace QuizFactory.Data.Migrations { using System; using System.Data.Entity.Migrations; using System.Linq; using QuizFactory.Data; internal sealed class Configuration : DbMigrationsConfiguration<QuizFactoryDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = false; } protected override void Seed(QuizFactoryDbContext context) { if (!context.Roles.Any()) { var seedUsers = new SeedUsers(); seedUsers.Generate(context); } var seedData = new SeedData(context); if (!context.QuizDefinitions.Any()) { foreach (var item in seedData.Quizzes) { context.QuizDefinitions.Add(item); } } if (!context.Categories.Any()) { foreach (var item in seedData.Categories) { context.Categories.Add(item); } } context.SaveChanges(); } } }``` Revert "disable automatic migration data loss"
```c# namespace QuizFactory.Data.Migrations { using System; using System.Data.Entity.Migrations; using System.Linq; using QuizFactory.Data; internal sealed class Configuration : DbMigrationsConfiguration<QuizFactoryDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(QuizFactoryDbContext context) { if (!context.Roles.Any()) { var seedUsers = new SeedUsers(); seedUsers.Generate(context); } var seedData = new SeedData(context); if (!context.QuizDefinitions.Any()) { foreach (var item in seedData.Quizzes) { context.QuizDefinitions.Add(item); } } if (!context.Categories.Any()) { foreach (var item in seedData.Categories) { context.Categories.Add(item); } } context.SaveChanges(); } } }```
76baf323-2477-4f32-87b0-6c2925de2aaf
{ "language": "C#" }
```c# using AutoMapper; using MediatR; using SupportManager.DAL; using SupportManager.Web.Infrastructure.CommandProcessing; namespace SupportManager.Web.Features.User { public class CreateCommandHandler : RequestHandler<CreateCommand> { private readonly SupportManagerContext db; public CreateCommandHandler(SupportManagerContext db) { this.db = db; } protected override void HandleCore(CreateCommand message) { var user = Mapper.Map<DAL.User>(message); db.Users.Add(user); } } }``` Replace map with manual initialization
```c# using SupportManager.DAL; using SupportManager.Web.Infrastructure.CommandProcessing; namespace SupportManager.Web.Features.User { public class CreateCommandHandler : RequestHandler<CreateCommand> { private readonly SupportManagerContext db; public CreateCommandHandler(SupportManagerContext db) { this.db = db; } protected override void HandleCore(CreateCommand message) { var user = new DAL.User {DisplayName = message.Name, Login = message.Name}; db.Users.Add(user); } } }```
ef316a83-affc-496a-a34b-499ba586a725
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class NicholasMGetchell : IAmACommunityMember { public string FirstName => "Nicholas"; public string LastName => "Getchell"; public string ShortBioOrTagLine => "Analyst"; public string StateOrRegion => "Boston, MA"; public string EmailAddress => "nicholas@getchell.org"; public string TwitterHandle => "getch3028"; public string GravatarHash => "1ebff516aa68c1b3bc786bd291b8fca1"; public string GitHubHandle => "ngetchell"; public GeoPosition Position => new GeoPosition(53.073635, 8.806422); public Uri WebSite => new Uri("https://powershell.getchell.org"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://powershell.getchell.org/feed/"); } } public string FeedLanguageCode => "en"; } } ``` Move from powershell.getchell.org to ngetchell.com
```c# using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class NicholasMGetchell : IAmACommunityMember { public string FirstName => "Nicholas"; public string LastName => "Getchell"; public string ShortBioOrTagLine => "Systems Administrator"; public string StateOrRegion => "Boston, MA"; public string EmailAddress => "nicholas@getchell.org"; public string TwitterHandle => "getch3028"; public string GravatarHash => "1ebff516aa68c1b3bc786bd291b8fca1"; public string GitHubHandle => "ngetchell"; public GeoPosition Position => new GeoPosition(53.073635, 8.806422); public Uri WebSite => new Uri("https://ngetchell.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ngetchell.com/tag/powershell/rss/"); } } public string FeedLanguageCode => "en"; } } ```
e3ad6ff3-dd6a-42d8-ae5e-7e47c2a956b6
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; namespace Storage.Net.Microsoft.Azure.DataLake.Store.Gen2.Models { public class DirectoryItem { [JsonProperty("contentLength")] public int? ContentLength { get; set; } [JsonProperty("etag")] public DateTime Etag { get; set; } [JsonProperty("group")] public string Group { get; set; } [JsonProperty("isDirectory")] public bool IsDirectory { get; set; } [JsonProperty("lastModified")] public DateTime LastModified { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("owner")] public string Owner { get; set; } [JsonProperty("permissions")] public string Permissions { get; set; } } }``` Change etag from DateTime to string, to reflect updated api.
```c# using System; using Newtonsoft.Json; namespace Storage.Net.Microsoft.Azure.DataLake.Store.Gen2.Models { public class DirectoryItem { [JsonProperty("contentLength")] public int? ContentLength { get; set; } [JsonProperty("etag")] public string Etag { get; set; } [JsonProperty("group")] public string Group { get; set; } [JsonProperty("isDirectory")] public bool IsDirectory { get; set; } [JsonProperty("lastModified")] public DateTime LastModified { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("owner")] public string Owner { get; set; } [JsonProperty("permissions")] public string Permissions { get; set; } } }```
4c7892aa-1e25-4689-b781-760930be66a1
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; namespace Umbraco.Web.WebApi.Filters { /// <summary> /// Allows an Action to execute with an arbitrary number of QueryStrings /// </summary> /// <remarks> /// Just like you can POST an arbitrary number of parameters to an Action, you can't GET an arbitrary number /// but this will allow you to do it /// </remarks> public sealed class HttpQueryStringModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { //get the query strings from the request properties if (actionContext.Request.Properties.ContainsKey("MS_QueryNameValuePairs")) { if (actionContext.Request.Properties["MS_QueryNameValuePairs"] is IEnumerable<KeyValuePair<string, string>> queryStrings) { var queryStringKeys = queryStrings.Select(kvp => kvp.Key).ToArray(); var additionalParameters = new Dictionary<string, string>(); if(queryStringKeys.Contains("culture") == false) { additionalParameters["culture"] = actionContext.Request.ClientCulture(); } var formData = new FormDataCollection(queryStrings.Union(additionalParameters)); bindingContext.Model = formData; return true; } } return false; } } } ``` Use InvariantContains instead of Contains when looking for culture in the querystring
```c# using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; using Umbraco.Core; namespace Umbraco.Web.WebApi.Filters { /// <summary> /// Allows an Action to execute with an arbitrary number of QueryStrings /// </summary> /// <remarks> /// Just like you can POST an arbitrary number of parameters to an Action, you can't GET an arbitrary number /// but this will allow you to do it /// </remarks> public sealed class HttpQueryStringModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { //get the query strings from the request properties if (actionContext.Request.Properties.ContainsKey("MS_QueryNameValuePairs")) { if (actionContext.Request.Properties["MS_QueryNameValuePairs"] is IEnumerable<KeyValuePair<string, string>> queryStrings) { var queryStringKeys = queryStrings.Select(kvp => kvp.Key).ToArray(); var additionalParameters = new Dictionary<string, string>(); if(queryStringKeys.InvariantContains("culture") == false) { additionalParameters["culture"] = actionContext.Request.ClientCulture(); } var formData = new FormDataCollection(queryStrings.Union(additionalParameters)); bindingContext.Model = formData; return true; } } return false; } } } ```
b5339b36-36be-476d-be38-e7801561e853
{ "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(); } } } ```
6e8c61f0-46d8-4124-ad9d-41e719701ad7
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TsAnalyser")] [assembly: AssemblyDescription("RTP and TS Analyser")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cinegy GmbH")] [assembly: AssemblyProduct("TsAnalyser")] [assembly: AssemblyCopyright("Copyright © Cinegy GmbH 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("4583a25c-d61a-44a3-b839-a55b091f6187")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Update assembly version number to v1.1
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TsAnalyser")] [assembly: AssemblyDescription("RTP and TS Analyser")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cinegy GmbH")] [assembly: AssemblyProduct("TsAnalyser")] [assembly: AssemblyCopyright("Copyright © Cinegy GmbH 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("4583a25c-d61a-44a3-b839-a55b091f6187")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] ```
81be36b6-f29a-4893-a756-c141c8ba0c5f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Solomobro.Instagram.Tests.WebApi { [TestFixture] public class AuthSettingsTests { //WebApiDemo.Settings.EnvironmentManager. } } ``` Add unit test for AuthSettings class
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Solomobro.Instagram.WebApiDemo.Settings; namespace Solomobro.Instagram.Tests.WebApi { [TestFixture] public class AuthSettingsTests { const string Settings = @"#Instagram Settings InstaWebsiteUrl=https://github.com/solomobro/Instagram InstaClientId=<CLIENT-ID> InstaClientSecret=<CLIENT-SECRET> InstaRedirectUrl=http://localhost:56841/api/authorize"; [Test] public void AllAuthSettingsPropertiesAreSet() { Assert.That(AuthSettings.InstaClientId, Is.Null); Assert.That(AuthSettings.InstaClientSecret, Is.Null); Assert.That(AuthSettings.InstaRedirectUrl, Is.Null); Assert.That(AuthSettings.InstaWebsiteUrl, Is.Null); using (var memStream = new MemoryStream(Encoding.ASCII.GetBytes(Settings))) { AuthSettings.LoadSettings(memStream); } Assert.That(AuthSettings.InstaClientId, Is.Not.Null); Assert.That(AuthSettings.InstaClientSecret, Is.Not.Null); Assert.That(AuthSettings.InstaRedirectUrl, Is.Not.Null); Assert.That(AuthSettings.InstaWebsiteUrl, Is.Not.Null); } } } ```
29c361fd-36bb-4fc9-abe8-d5ccd9d02e06
{ "language": "C#" }
```c# using System; namespace MultiMiner.Xgminer { //marked Serializable to allow deep cloning of CoinConfiguration [Serializable] public class MiningPool { public string Host { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public int Quota { get; set; } //see bfgminer README about quotas } } ``` Set default values (to avoid null references for invalid user data)
```c# using System; namespace MultiMiner.Xgminer { //marked Serializable to allow deep cloning of CoinConfiguration [Serializable] public class MiningPool { public MiningPool() { //set defaults Host = String.Empty; Username = String.Empty; Password = String.Empty; } public string Host { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public int Quota { get; set; } //see bfgminer README about quotas } } ```
900f819d-6930-4e59-b638-b68d1fd2432e
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; namespace NuGet { public static class PackageIdValidator { internal const int MaxPackageIdLength = 100; public static bool IsValidPackageId(string packageId) { if (string.IsNullOrWhiteSpace(packageId)) { throw new ArgumentException(nameof(packageId)); } // Rules: // Should start with a character // Can be followed by '.' or '-'. Cannot have 2 of these special characters consecutively. // Cannot end with '-' or '.' var firstChar = packageId[0]; if (!char.IsLetterOrDigit(firstChar) && firstChar != '_') { // Should start with a char/digit/_. return false; } var lastChar = packageId[packageId.Length - 1]; if (lastChar == '-' || lastChar == '.') { // Should not end with a '-' or '.'. return false; } for (int index = 1; index < packageId.Length - 1; index++) { var ch = packageId[index]; if (!char.IsLetterOrDigit(ch) && ch != '-' && ch != '.') { return false; } if ((ch == '-' || ch == '.') && ch == packageId[index - 1]) { // Cannot have two successive '-' or '.' in the name. return false; } } return true; } public static void ValidatePackageId(string packageId) { if (packageId.Length > MaxPackageIdLength) { // TODO: Resources throw new ArgumentException("NuGetResources.Manifest_IdMaxLengthExceeded"); } if (!IsValidPackageId(packageId)) { // TODO: Resources throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "NuGetResources.InvalidPackageId", packageId)); } } } }``` Fix package id version checking during pack - The logic wasn't in sync with nuget.exe
```c# // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using System.Text.RegularExpressions; namespace NuGet { public static class PackageIdValidator { private static readonly Regex _idRegex = new Regex(@"^\w+([_.-]\w+)*$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); internal const int MaxPackageIdLength = 100; public static bool IsValidPackageId(string packageId) { if (packageId == null) { throw new ArgumentNullException("packageId"); } return _idRegex.IsMatch(packageId); } public static void ValidatePackageId(string packageId) { if (packageId.Length > MaxPackageIdLength) { // TODO: Resources throw new ArgumentException("NuGetResources.Manifest_IdMaxLengthExceeded"); } if (!IsValidPackageId(packageId)) { // TODO: Resources throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "NuGetResources.InvalidPackageId", packageId)); } } } }```
e9051524-3ee4-417f-ae6d-6781b964ef24
{ "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.1.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.CommonServiceLocator 3.0.1")] ``` 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.1.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.CommonServiceLocator 3.0.1")] ```
bb818d4d-301f-45af-8338-bf350b3a5fbd
{ "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.2.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.AggregateService 3.0.2")] ``` 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.2.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.AggregateService 3.0.2")] ```
386e4b1c-689e-4ba5-bd0d-4d79b5b56073
{ "language": "C#" }
```c# // <copyright file="PackageBuildList.cs" company="Mark Final"> // Opus // </copyright> // <summary>Opus Core</summary> // <author>Mark Final</author> namespace Opus.Core { public class PackageBuild { public PackageBuild(PackageIdentifier id) { this.Name = id.Name; this.Versions = new UniqueList<PackageIdentifier>(); this.Versions.Add(id); this.SelectedVersion = id; } public string Name { get; private set; } public UniqueList<PackageIdentifier> Versions { get; private set; } public PackageIdentifier SelectedVersion { get; set; } } public class PackageBuildList : UniqueList<PackageBuild> { public PackageBuild GetPackage(string name) { foreach (PackageBuild i in this) { if (i.Name == name) { return i; } } return null; } } }``` Add an improved string representation of PackageBuild instances
```c# // <copyright file="PackageBuildList.cs" company="Mark Final"> // Opus // </copyright> // <summary>Opus Core</summary> // <author>Mark Final</author> namespace Opus.Core { public class PackageBuild { public PackageBuild(PackageIdentifier id) { this.Name = id.Name; this.Versions = new UniqueList<PackageIdentifier>(); this.Versions.Add(id); this.SelectedVersion = id; } public string Name { get; private set; } public UniqueList<PackageIdentifier> Versions { get; private set; } public PackageIdentifier SelectedVersion { get; set; } public override string ToString() { System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.AppendFormat("{0}: Package '{1}' with {2} versions", base.ToString(), this.Name, this.Versions.Count); return builder.ToString(); } } public class PackageBuildList : UniqueList<PackageBuild> { public PackageBuild GetPackage(string name) { foreach (PackageBuild i in this) { if (i.Name == name) { return i; } } return null; } } }```
c44e5dc1-a64e-470a-921d-bc0455b5b4a0
{ "language": "C#" }
```c# // Copyright 2020 Jon Skeet. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Newtonsoft.Json; using System; using VDrumExplorer.Utility; namespace VDrumExplorer.Model.Schema.Json { internal class HexInt32Converter : JsonConverter<HexInt32> { public override void WriteJson(JsonWriter writer, HexInt32 value, JsonSerializer serializer) => writer.WriteValue(value.ToString()); public override HexInt32 ReadJson(JsonReader reader, Type objectType, HexInt32 existingValue, bool hasExistingValue, JsonSerializer serializer) => HexInt32.Parse(Preconditions.AssertNotNull((string?) reader.Value)); } } ``` Fix new warning around nullability
```c# // Copyright 2020 Jon Skeet. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Newtonsoft.Json; using System; using VDrumExplorer.Utility; namespace VDrumExplorer.Model.Schema.Json { internal class HexInt32Converter : JsonConverter<HexInt32> { public override void WriteJson(JsonWriter writer, HexInt32? value, JsonSerializer serializer) => writer.WriteValue(value?.ToString()); public override HexInt32 ReadJson(JsonReader reader, Type objectType, HexInt32? existingValue, bool hasExistingValue, JsonSerializer serializer) => HexInt32.Parse(Preconditions.AssertNotNull((string?) reader.Value)); } } ```
93c6902f-d302-464a-8775-f861aac07fb0
{ "language": "C#" }
```c# using HarryPotterUnity.Game; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.PlayRequirements { public class InputRequirement : MonoBehaviour, ICardPlayRequirement { private BaseCard _cardInfo; [SerializeField, UsedImplicitly] private int _fromHandActionInputRequired; [SerializeField, UsedImplicitly] private int _inPlayActionInputRequired; public int FromHandActionInputRequired { get { return _fromHandActionInputRequired; } } public int InPlayActionInputRequired { get { return _inPlayActionInputRequired; } } private void Awake() { _cardInfo = GetComponent<BaseCard>(); if (GetComponent<InputGatherer>() == null) { gameObject.AddComponent<InputGatherer>(); } } public bool MeetsRequirement() { return _cardInfo.GetFromHandActionTargets().Count >= _fromHandActionInputRequired; } public void OnRequirementMet() { } } } ``` Add TODO for Input Requirement
```c# using HarryPotterUnity.Game; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.PlayRequirements { public class InputRequirement : MonoBehaviour, ICardPlayRequirement { private BaseCard _cardInfo; [SerializeField, UsedImplicitly] private int _fromHandActionInputRequired; [SerializeField, UsedImplicitly] private int _inPlayActionInputRequired; public int FromHandActionInputRequired { get { return _fromHandActionInputRequired; } } public int InPlayActionInputRequired { get { return _inPlayActionInputRequired; } } private void Awake() { _cardInfo = GetComponent<BaseCard>(); if (GetComponent<InputGatherer>() == null) { gameObject.AddComponent<InputGatherer>(); } } public bool MeetsRequirement() { //TODO: Need to check whether this needs to check the FromHandActionTargets or the InPlayActionTargets! return _cardInfo.GetFromHandActionTargets().Count >= _fromHandActionInputRequired; } public void OnRequirementMet() { } } } ```
5359e40c-fca9-4b58-b762-fa4f60f64325
{ "language": "C#" }
```c# namespace System { /// <summary> /// Represents a 32-bit integer. /// </summary> public struct Int32 { // Note: integers are equivalent to instances of this data structure because // flame-llvm the contents of single-field structs as a value of their single // field, rather than as a LLVM struct. So a 32-bit integer becomes an i32 and // so does a `System.Int32`. So don't add, remove, or edit the fields in this // struct. private int value; /// <summary> /// Converts this integer to a string representation. /// </summary> /// <returns>The string representation for the integer.</returns> public string ToString() { return Convert.ToString(value); } } }``` Fix a typo in a comment
```c# namespace System { /// <summary> /// Represents a 32-bit integer. /// </summary> public struct Int32 { // Note: integers are equivalent to instances of this data structure because // flame-llvm stores the contents of single-field structs as a value of their // field, rather than as a LLVM struct. So a 32-bit integer becomes an i32 and // so does a `System.Int32`. So don't add, remove, or edit the fields in this // struct. private int value; /// <summary> /// Converts this integer to a string representation. /// </summary> /// <returns>The string representation for the integer.</returns> public string ToString() { return Convert.ToString(value); } } }```
25c97676-bf4d-49e1-bbee-b52110d6bdec
{ "language": "C#" }
```c# using Android.App; using Android.OS; using MvvmCross.Droid.Support.V7.AppCompat; using System; namespace ExpandableList.Droid.Views { [Activity(Label = "DetailsView")] public class DetailsView : MvxAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { try { base.OnCreate(savedInstanceState); } catch (Exception ex) { } } } }``` Fix build error with unused variable
```c# using Android.App; using Android.OS; using MvvmCross.Droid.Support.V7.AppCompat; using System; namespace ExpandableList.Droid.Views { [Activity(Label = "DetailsView")] public class DetailsView : MvxAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); } } }```
72f01018-a184-4045-9e59-267d085a2055
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Audio; using osu.Framework.IO.Stores; using osu.Framework.Threading; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioComponentTest { [Test] public void TestVirtualTrack() { var thread = new AudioThread(); var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.dll"), @"Resources"); var manager = new AudioManager(thread, store, store); thread.Start(); var track = manager.Tracks.GetVirtual(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(0, track.CurrentTime); track.Start(); Task.Delay(50); Assert.Greater(track.CurrentTime, 0); track.Stop(); Assert.IsFalse(track.IsRunning); thread.Exit(); Task.Delay(500); Assert.IsFalse(thread.Exited); } } } ``` Fix new test on CI host
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Audio; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Framework.Threading; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioComponentTest { [Test] public void TestVirtualTrack() { Architecture.SetIncludePath(); var thread = new AudioThread(); var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.dll"), @"Resources"); var manager = new AudioManager(thread, store, store); thread.Start(); var track = manager.Tracks.GetVirtual(); Assert.IsFalse(track.IsRunning); Assert.AreEqual(0, track.CurrentTime); track.Start(); Task.Delay(50); Assert.Greater(track.CurrentTime, 0); track.Stop(); Assert.IsFalse(track.IsRunning); thread.Exit(); Task.Delay(500); Assert.IsFalse(thread.Exited); } } } ```
e25662af-b611-4274-91cf-225e0900301b
{ "language": "C#" }
```c# using System.Windows; using Arkivverket.Arkade.UI.Views; using Arkivverket.Arkade.Util; using Autofac; using Prism.Autofac; using Prism.Modularity; namespace Arkivverket.Arkade.UI { public class Bootstrapper : AutofacBootstrapper { protected override DependencyObject CreateShell() { return Container.Resolve<MainWindow>(); } protected override void InitializeShell() { Application.Current.MainWindow.Show(); } protected override void ConfigureModuleCatalog() { var catalog = (ModuleCatalog) ModuleCatalog; catalog.AddModule(typeof(ModuleAModule)); } protected override void ConfigureContainerBuilder(ContainerBuilder builder) { base.ConfigureContainerBuilder(builder); builder.RegisterModule(new ArkadeAutofacModule()); } } /* public class Bootstrapper : UnityBootstrapper { protected override DependencyObject CreateShell() { return Container.Resolve<MainWindow>(); } protected override void InitializeShell() { Application.Current.MainWindow.Show(); } protected override void ConfigureContainer() { base.ConfigureContainer(); Container.RegisterTypeForNavigation<View000Debug>("View000Debug"); Container.RegisterTypeForNavigation<View100Status>("View100Status"); ILogService logService = new RandomLogService(); Container.RegisterInstance(logService); } protected override void ConfigureModuleCatalog() { ModuleCatalog catalog = (ModuleCatalog)ModuleCatalog; catalog.AddModule(typeof(ModuleAModule)); } } public static class UnityExtensons { public static void RegisterTypeForNavigation<T>(this IUnityContainer container, string name) { container.RegisterType(typeof(object), typeof(T), name); } } */ }``` Remove old bootstrapper stuff from UI-project.
```c# using System.Windows; using Arkivverket.Arkade.UI.Views; using Arkivverket.Arkade.Util; using Autofac; using Prism.Autofac; using Prism.Modularity; namespace Arkivverket.Arkade.UI { public class Bootstrapper : AutofacBootstrapper { protected override DependencyObject CreateShell() { return Container.Resolve<MainWindow>(); } protected override void InitializeShell() { Application.Current.MainWindow.Show(); } protected override void ConfigureModuleCatalog() { var catalog = (ModuleCatalog) ModuleCatalog; catalog.AddModule(typeof(ModuleAModule)); } protected override void ConfigureContainerBuilder(ContainerBuilder builder) { base.ConfigureContainerBuilder(builder); builder.RegisterModule(new ArkadeAutofacModule()); } } }```
df61088c-ca46-445d-8af1-71174ce4149b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace Totem.Runtime.Timeline { /// <summary> /// Describes the database persisting the timeline /// </summary> public interface ITimelineDb { Many<TimelinePoint> Append(TimelinePosition cause, Many<Event> events); TimelinePoint AppendOccurred(TimelinePoint scheduledPoint); void RemoveFromSchedule(TimelinePosition position); TimelineResumeInfo ReadResumeInfo(); } }``` Remove unused method on timeline db
```c# using System; using System.Collections.Generic; using System.Linq; namespace Totem.Runtime.Timeline { /// <summary> /// Describes the database persisting the timeline /// </summary> public interface ITimelineDb { Many<TimelinePoint> Append(TimelinePosition cause, Many<Event> events); TimelinePoint AppendOccurred(TimelinePoint scheduledPoint); TimelineResumeInfo ReadResumeInfo(); } }```
e42dd004-ad8d-4502-87ad-90ee6a7b37b3
{ "language": "C#" }
```c# namespace Nancy.Session { using System.Collections; using System.Collections.Generic; public class Session : ISession { private readonly IDictionary<string, object> dictionary; private bool hasChanged; public Session() : this(new Dictionary<string, object>(0)){} public Session(IDictionary<string, object> dictionary) { this.dictionary = dictionary; } public int Count { get { return dictionary.Count; } } public void DeleteAll() { if (Count > 0) { MarkAsChanged(); } dictionary.Clear(); } public void Delete(string key) { if (dictionary.Remove(key)) { MarkAsChanged(); } } public object this[string key] { get { return dictionary.ContainsKey(key) ? dictionary[key] : null; } set { dictionary[key] = value; MarkAsChanged(); } } public bool HasChanged { get { return this.hasChanged; } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return dictionary.GetEnumerator(); } private void MarkAsChanged() { hasChanged = true; } } }``` Update session only is value is changed
```c# namespace Nancy.Session { using System.Collections; using System.Collections.Generic; public class Session : ISession { private readonly IDictionary<string, object> dictionary; private bool hasChanged; public Session() : this(new Dictionary<string, object>(0)){} public Session(IDictionary<string, object> dictionary) { this.dictionary = dictionary; } public int Count { get { return dictionary.Count; } } public void DeleteAll() { if (Count > 0) { MarkAsChanged(); } dictionary.Clear(); } public void Delete(string key) { if (dictionary.Remove(key)) { MarkAsChanged(); } } public object this[string key] { get { return dictionary.ContainsKey(key) ? dictionary[key] : null; } set { if (this[key] == value) return; dictionary[key] = value; MarkAsChanged(); } } public bool HasChanged { get { return this.hasChanged; } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return dictionary.GetEnumerator(); } private void MarkAsChanged() { hasChanged = true; } } }```
810f07ec-2b5f-4e79-8f79-7cf326ab237d
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Video; using osu.Game.Graphics; namespace osu.Game.Tournament.Components { public class TourneyVideo : CompositeDrawable { private readonly VideoSprite video; public TourneyVideo(Stream stream) { if (stream == null) { InternalChild = new Box { Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.3f), OsuColour.Gray(0.6f)), RelativeSizeAxes = Axes.Both, }; } else InternalChild = video = new VideoSprite(stream) { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fit, }; } public bool Loop { set { if (video != null) video.Loop = value; } } } } ``` Fix tournament videos stuttering when changing scenes
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Video; using osu.Framework.Timing; using osu.Game.Graphics; namespace osu.Game.Tournament.Components { public class TourneyVideo : CompositeDrawable { private readonly VideoSprite video; private ManualClock manualClock; private IFrameBasedClock sourceClock; public TourneyVideo(Stream stream) { if (stream == null) { InternalChild = new Box { Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.3f), OsuColour.Gray(0.6f)), RelativeSizeAxes = Axes.Both, }; } else InternalChild = video = new VideoSprite(stream) { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fit, }; } public bool Loop { set { if (video != null) video.Loop = value; } } protected override void LoadComplete() { base.LoadComplete(); sourceClock = Clock; Clock = new FramedClock(manualClock = new ManualClock()); } protected override void Update() { base.Update(); // we want to avoid seeking as much as possible, because we care about performance, not sync. // to avoid seeking completely, we only increment out local clock when in an updating state. manualClock.CurrentTime += sourceClock.ElapsedFrameTime; } } } ```
c931d87e-e245-4971-9f81-8f6e4d959e35
{ "language": "C#" }
```c# using UnityEngine; public class RoomGenerator : MonoBehaviour { public GameObject roomPrefab; public int roomCount = 100; public int spaceWidth = 500; public int spaceLength = 500; public int minRoomWidth = 5; public int maxRoomWidth = 20; public int minRoomLength = 5; public int maxRoomLength = 20; public Room[] generatedrRooms; public void Run() { for (int i = 0; i < this.transform.childCount; i++) { DestroyImmediate(this.transform.GetChild(i).gameObject); } generatedrRooms = new Room[roomCount]; for (int i = 0; i < roomCount; i++) { var posX = Random.Range (0, spaceWidth); var posZ = Random.Range (0, spaceLength); var sizeX = Random.Range (minRoomWidth, maxRoomWidth); var sizeZ = Random.Range (minRoomLength, maxRoomLength); var instance = Instantiate (roomPrefab); instance.transform.SetParent (this.transform); instance.transform.localPosition = new Vector3 (posX, 0f, posZ); instance.transform.localScale = Vector3.one; var room = instance.GetComponent<Room> (); room.Init (sizeX, sizeZ); generatedrRooms [i] = room; } } } ``` Fix typo in public variable
```c# using UnityEngine; public class RoomGenerator : MonoBehaviour { public GameObject roomPrefab; public int roomCount = 100; public int spaceWidth = 500; public int spaceLength = 500; public int minRoomWidth = 5; public int maxRoomWidth = 20; public int minRoomLength = 5; public int maxRoomLength = 20; public Room[] generatedRooms; public void Run() { for (int i = 0; i < generatedRooms.Length; i++) { DestroyImmediate(generatedRooms[i].gameObject); } generatedRooms = new Room[roomCount]; for (int i = 0; i < roomCount; i++) { var posX = Random.Range (0, spaceWidth); var posZ = Random.Range (0, spaceLength); var sizeX = Random.Range (minRoomWidth, maxRoomWidth); var sizeZ = Random.Range (minRoomLength, maxRoomLength); var instance = Instantiate (roomPrefab); instance.transform.SetParent (this.transform); instance.transform.localPosition = new Vector3 (posX, 0f, posZ); instance.transform.localScale = Vector3.one; var room = instance.GetComponent<Room> (); room.Init (sizeX, sizeZ); generatedRooms [i] = room; } } } ```
45946d66-96d1-44a1-94f5-582497e4b46b
{ "language": "C#" }
```c# using System; using DeployStatus.Configuration; using DeployStatus.SignalR; using log4net; using Microsoft.Owin.Hosting; namespace DeployStatus.Service { public class DeployStatusService : IService { private IDisposable webApp; private readonly ILog log; private readonly DeployStatusConfiguration deployConfiguration; public DeployStatusService() { log = LogManager.GetLogger(typeof (DeployStatusService)); deployConfiguration = DeployStatusSettingsSection.Settings.AsDeployConfiguration(); } public void Start() { log.Info("Starting api polling service..."); DeployStatusState.Instance.Value.Start(deployConfiguration); var webAppUrl = deployConfiguration.WebAppUrl; log.Info($"Starting web app service on {webAppUrl}..."); webApp = WebApp.Start<Startup>(webAppUrl); log.Info("Started."); } public void Stop() { webApp.Dispose(); DeployStatusState.Instance.Value.Stop(); } } }``` Add support for listening on multiple urls.
```c# using System; using System.Linq; using DeployStatus.Configuration; using DeployStatus.SignalR; using log4net; using Microsoft.Owin.Hosting; namespace DeployStatus.Service { public class DeployStatusService : IService { private IDisposable webApp; private readonly ILog log; private readonly DeployStatusConfiguration deployConfiguration; public DeployStatusService() { log = LogManager.GetLogger(typeof (DeployStatusService)); deployConfiguration = DeployStatusSettingsSection.Settings.AsDeployConfiguration(); } public void Start() { log.Info("Starting api polling service..."); DeployStatusState.Instance.Value.Start(deployConfiguration); var webAppUrl = deployConfiguration.WebAppUrl; log.Info($"Starting web app service on {webAppUrl}..."); var startOptions = new StartOptions(); foreach (var url in webAppUrl.Split(',')) { startOptions.Urls.Add(url); } webApp = WebApp.Start<Startup>(startOptions); log.Info("Started."); } public void Stop() { webApp.Dispose(); DeployStatusState.Instance.Value.Stop(); } } }```
7e6d5e0a-09f7-4464-b431-22f3bed55548
{ "language": "C#" }
```c# using System; using System.Windows.Controls; using GitHub.InlineReviews.Views; using GitHub.InlineReviews.ViewModels; namespace GitHub.InlineReviews.Tags { public partial class ShowInlineCommentGlyph : UserControl { readonly CommentTooltipView commentTooltipView; public ShowInlineCommentGlyph() { InitializeComponent(); commentTooltipView = new CommentTooltipView(); ToolTip = commentTooltipView; ToolTipOpening += ShowInlineCommentGlyph_ToolTipOpening; } private void ShowInlineCommentGlyph_ToolTipOpening(object sender, ToolTipEventArgs e) { var tag = Tag as ShowInlineCommentTag; var viewModel = new CommentTooltipViewModel(); foreach (var comment in tag.Thread.Comments) { var commentViewModel = new TooltipCommentViewModel(comment.User, comment.Body, comment.CreatedAt); viewModel.Comments.Add(commentViewModel); } commentTooltipView.DataContext = viewModel; } } } ``` Create and release tooltip content on demand
```c# using System; using System.Windows.Controls; using GitHub.InlineReviews.Views; using GitHub.InlineReviews.ViewModels; namespace GitHub.InlineReviews.Tags { public partial class ShowInlineCommentGlyph : UserControl { readonly ToolTip toolTip; public ShowInlineCommentGlyph() { InitializeComponent(); toolTip = new ToolTip(); ToolTip = toolTip; } protected override void OnToolTipOpening(ToolTipEventArgs e) { var tag = Tag as ShowInlineCommentTag; var viewModel = new CommentTooltipViewModel(); foreach (var comment in tag.Thread.Comments) { var commentViewModel = new TooltipCommentViewModel(comment.User, comment.Body, comment.CreatedAt); viewModel.Comments.Add(commentViewModel); } var view = new CommentTooltipView(); view.DataContext = viewModel; toolTip.Content = view; } protected override void OnToolTipClosing(ToolTipEventArgs e) { toolTip.Content = null; } } } ```
f39ac870-c17e-489f-8a7d-98059345be62
{ "language": "C#" }
```c# using System.Collections.Generic; namespace Umbraco.Web.Media.EmbedProviders { public class YouTube : EmbedProviderBase { public override string ApiEndpoint => "https://www.youtube.com/oembed"; public override string[] UrlSchemeRegex => new string[] { @"youtu.be/.*", @"youtu.be/.*" }; public override Dictionary<string, string> RequestParams => new Dictionary<string, string>() { //ApiUrl/?format=json {"format", "json"} }; public override string GetMarkup(string url, int maxWidth = 0, int maxHeight = 0) { var requestUrl = base.GetEmbedProviderUrl(url, maxWidth, maxHeight); var oembed = base.GetJsonResponse<OEmbedResponse>(requestUrl); return oembed.GetHtml(); } } } ``` Fix up youtube URL regex matching
```c# using System.Collections.Generic; namespace Umbraco.Web.Media.EmbedProviders { public class YouTube : EmbedProviderBase { public override string ApiEndpoint => "https://www.youtube.com/oembed"; public override string[] UrlSchemeRegex => new string[] { @"youtu.be/.*", @"youtube.com/watch.*" }; public override Dictionary<string, string> RequestParams => new Dictionary<string, string>() { //ApiUrl/?format=json {"format", "json"} }; public override string GetMarkup(string url, int maxWidth = 0, int maxHeight = 0) { var requestUrl = base.GetEmbedProviderUrl(url, maxWidth, maxHeight); var oembed = base.GetJsonResponse<OEmbedResponse>(requestUrl); return oembed.GetHtml(); } } } ```
e0d5b908-0bf8-4117-ac14-cfb427dfe56d
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; namespace ErgastApi.Responses { // TODO: Use internal/private constructors for all response types? public abstract class ErgastResponse { [JsonProperty("url")] public virtual string RequestUrl { get; private set; } [JsonProperty("limit")] public virtual int Limit { get; private set; } [JsonProperty("offset")] public virtual int Offset { get; private set; } [JsonProperty("total")] public virtual int TotalResults { get; private set; } // TODO: Note that it can be inaccurate if limit/offset do not correlate // TODO: Test with 0 values public virtual int Page => Offset / Limit + 1; // TODO: Test with 0 values public virtual int TotalPages => (int) Math.Ceiling(TotalResults / (double)Limit); // TODO: Test public virtual bool HasMorePages => TotalResults > Limit + Offset; } } ``` Fix issue with Page calculation
```c# using System; using Newtonsoft.Json; namespace ErgastApi.Responses { // TODO: Use internal/private constructors for all response types? public abstract class ErgastResponse { [JsonProperty("url")] public string RequestUrl { get; protected set; } [JsonProperty("limit")] public int Limit { get; protected set; } [JsonProperty("offset")] public int Offset { get; protected set; } [JsonProperty("total")] public int TotalResults { get; protected set; } // TODO: Note that it can be inaccurate if limit/offset do not divide evenly public int Page { get { if (Limit <= 0) return 1; return (int) Math.Ceiling((double) Offset / Limit) + 1; } } // TODO: Test with 0 values public int TotalPages => (int) Math.Ceiling(TotalResults / (double) Limit); // TODO: Test public bool HasMorePages => TotalResults > Limit + Offset; } } ```
00881bad-08a1-4388-9da4-0cb941d541dc
{ "language": "C#" }
```c# using System.Linq; using System.Text; namespace Modbus.IO { internal static class StreamResourceUtility { internal static string ReadLine(IStreamResource stream) { var result = new StringBuilder(); var singleByteBuffer = new byte[1]; do { stream.Read(singleByteBuffer, 0, 1); result.Append(Encoding.ASCII.GetChars(singleByteBuffer).First()); } while (!result.ToString().EndsWith(Modbus.NewLine)); return result.ToString().Substring(0, result.Length - Modbus.NewLine.Length); } } }``` Add checking of Read() return value.
```c# using System.Linq; using System.Text; namespace Modbus.IO { internal static class StreamResourceUtility { internal static string ReadLine(IStreamResource stream) { var result = new StringBuilder(); var singleByteBuffer = new byte[1]; do { if (0 == stream.Read(singleByteBuffer, 0, 1)) continue; result.Append(Encoding.ASCII.GetChars(singleByteBuffer).First()); } while (!result.ToString().EndsWith(Modbus.NewLine)); return result.ToString().Substring(0, result.Length - Modbus.NewLine.Length); } } } ```
a7d828a6-5a28-4d74-8928-9c275ed18ddc
{ "language": "C#" }
```c# using GitHub.UI; using GitHub.VisualStudio.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace GitHub.VisualStudio { public static class SharedResources { static readonly Dictionary<string, DrawingBrush> drawingBrushes = new Dictionary<string, DrawingBrush>(); public static DrawingBrush GetDrawingForIcon(Octicon icon, Brush color) { string name = icon.ToString(); if (drawingBrushes.ContainsKey(name)) return drawingBrushes[name]; var brush = new DrawingBrush() { Drawing = new GeometryDrawing() { Brush = color, Pen = new Pen(color, 1.0).FreezeThis(), Geometry = OcticonPath.GetGeometryForIcon(icon).FreezeThis() } .FreezeThis(), Stretch = Stretch.Uniform } .FreezeThis(); drawingBrushes.Add(name, brush); return brush; } } } ``` Sort and remove unused usings
```c# using System.Collections.Generic; using System.Windows.Media; using GitHub.UI; using GitHub.VisualStudio.UI; namespace GitHub.VisualStudio { public static class SharedResources { static readonly Dictionary<string, DrawingBrush> drawingBrushes = new Dictionary<string, DrawingBrush>(); public static DrawingBrush GetDrawingForIcon(Octicon icon, Brush color) { string name = icon.ToString(); if (drawingBrushes.ContainsKey(name)) return drawingBrushes[name]; var brush = new DrawingBrush() { Drawing = new GeometryDrawing() { Brush = color, Pen = new Pen(color, 1.0).FreezeThis(), Geometry = OcticonPath.GetGeometryForIcon(icon).FreezeThis() } .FreezeThis(), Stretch = Stretch.Uniform } .FreezeThis(); drawingBrushes.Add(name, brush); return brush; } } } ```
eea2501f-a9c3-4b6a-ba20-fd0d343aff18
{ "language": "C#" }
```c# using Stylet.Samples.RedditBrowser.Events; using Stylet.Samples.RedditBrowser.RedditApi; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.RedditBrowser.Pages { public class TaskbarViewModel : Screen { private IEventAggregator events; public string Subreddit { get; set; } public IEnumerable<SortMode> SortModes { get; private set; } public SortMode SelectedSortMode { get; set; } public TaskbarViewModel(IEventAggregator events) { this.events = events; this.SortModes = SortMode.AllModes; this.SelectedSortMode = SortMode.Hot; } public void Open() { this.events.Publish(new OpenSubredditEvent() { Subreddit = this.Subreddit, SortMode = this.SelectedSortMode }); } } } ``` Add extra work to RedditBrowser sample
```c# using Stylet.Samples.RedditBrowser.Events; using Stylet.Samples.RedditBrowser.RedditApi; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.RedditBrowser.Pages { public class TaskbarViewModel : Screen { private IEventAggregator events; public string Subreddit { get; set; } public IEnumerable<SortMode> SortModes { get; private set; } public SortMode SelectedSortMode { get; set; } public TaskbarViewModel(IEventAggregator events) { this.events = events; this.SortModes = SortMode.AllModes; this.SelectedSortMode = SortMode.Hot; } public bool CanOpen { get { return !String.IsNullOrWhiteSpace(this.Subreddit); } } public void Open() { this.events.Publish(new OpenSubredditEvent() { Subreddit = this.Subreddit, SortMode = this.SelectedSortMode }); } } } ```
fa79b2bb-e9b5-488c-a88d-c5e9dab7bb5d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using XboxOnePadReader; namespace PadReaderTest { class Program { static void Main(string[] args) { ControllerReader myController = ControllerReader.Instance; int x = 0; while (x < 5) { Thread.Sleep(1); ++x; } myController.CloseController(); } } } ``` Fix Sleep of the test program
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using XboxOnePadReader; namespace PadReaderTest { class Program { static void Main(string[] args) { ControllerReader myController = ControllerReader.Instance; int x = 0; while (x < 5) { Thread.Sleep(1000); ++x; } myController.CloseController(); } } } ```
23b5ddb8-370e-475f-b560-ee96e44885fc
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test1 : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } } ``` Write Log message for test
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test1 : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { Condole.Log("This log is added by Suzuki"); } }```
06eb423d-069a-4414-a987-c4308d879e5f
{ "language": "C#" }
```c# namespace OpenKh.Game { public class Global { public const int ResolutionWidth = 512; public const int ResolutionHeight = 416; public const int ResolutionRemixWidth = 684; public const float ResolutionReMixRatio = 0.925f; public const float ResolutionBoostRatio = 2; } } ``` Remove unused line of code
```c# namespace OpenKh.Game { public class Global { public const int ResolutionWidth = 512; public const int ResolutionHeight = 416; public const int ResolutionRemixWidth = 684; public const float ResolutionReMixRatio = 0.925f; } } ```
a1340197-c2e4-4657-bdef-4b10ae1ea993
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Taiko.Difficulty; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Taiko.Tests { public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko"; [TestCase(2.9811338051242915d, "diffcalc-test")] [TestCase(2.9811338051242915d, "diffcalc-test-strong")] public void Test(double expected, string name) => base.Test(expected, name); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset(), beatmap); protected override Ruleset CreateRuleset() => new TaikoRuleset(); } } ``` Update expected SR in test
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Taiko.Difficulty; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Taiko.Tests { public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko"; [TestCase(2.2905937546434592d, "diffcalc-test")] [TestCase(2.2905937546434592d, "diffcalc-test-strong")] public void Test(double expected, string name) => base.Test(expected, name); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset(), beatmap); protected override Ruleset CreateRuleset() => new TaikoRuleset(); } } ```
ff267cfa-c770-4709-9629-68e382f8e185
{ "language": "C#" }
```c# using System; using System.Drawing.Imaging; using System.IO; using NUnit.Framework; using ValveResourceFormat; using ValveResourceFormat.ResourceTypes; namespace Tests { public class TextureTests { [Test] public void Test() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Textures"); var files = Directory.GetFiles(path, "*.vtex_c"); foreach (var file in files) { var resource = new Resource(); resource.Read(file); var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap(); using (var ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); using (var expected = new FileStream(Path.ChangeExtension(file, "png"), FileMode.Open, FileAccess.Read)) { FileAssert.AreEqual(expected, ms); } } } } } } ``` Disable text tests for now
```c# using System; using System.Drawing.Imaging; using System.IO; using NUnit.Framework; using ValveResourceFormat; using ValveResourceFormat.ResourceTypes; namespace Tests { public class TextureTests { [Test] [Ignore("Need a better way of testing images rather than comparing the files directly")] public void Test() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Textures"); var files = Directory.GetFiles(path, "*.vtex_c"); foreach (var file in files) { var resource = new Resource(); resource.Read(file); var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap(); using (var ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); using (var expected = new FileStream(Path.ChangeExtension(file, "png"), FileMode.Open, FileAccess.Read)) { FileAssert.AreEqual(expected, ms); } } } } } } ```
9854d64b-7093-4f67-a073-6ab1ecfb021b
{ "language": "C#" }
```c# using System; using Microsoft.AspNetCore.StaticFiles; using Swashbuckle.AspNetCore.SwaggerUI; namespace Microsoft.AspNetCore.Builder { public static class SwaggerUIBuilderExtensions { public static IApplicationBuilder UseSwaggerUI( this IApplicationBuilder app, Action<SwaggerUIOptions> setupAction) { var options = new SwaggerUIOptions(); setupAction?.Invoke(options); // Serve swagger-ui assets with the FileServer middleware, using a custom FileProvider // to inject parameters into "index.html" var fileServerOptions = new FileServerOptions { RequestPath = $"/{options.RoutePrefix}", FileProvider = new SwaggerUIFileProvider(options.IndexSettings.ToTemplateParameters()), EnableDefaultFiles = true, // serve index.html at /{options.RoutePrefix}/ }; fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider(); app.UseFileServer(fileServerOptions); return app; } } } ``` Support to map swagger UI to application root url
```c# using System; using Microsoft.AspNetCore.StaticFiles; using Swashbuckle.AspNetCore.SwaggerUI; namespace Microsoft.AspNetCore.Builder { public static class SwaggerUIBuilderExtensions { public static IApplicationBuilder UseSwaggerUI( this IApplicationBuilder app, Action<SwaggerUIOptions> setupAction) { var options = new SwaggerUIOptions(); setupAction?.Invoke(options); // Serve swagger-ui assets with the FileServer middleware, using a custom FileProvider // to inject parameters into "index.html" var fileServerOptions = new FileServerOptions { RequestPath = string.IsNullOrWhiteSpace(options.RoutePrefix) ? string.Empty : $"/{options.RoutePrefix}", FileProvider = new SwaggerUIFileProvider(options.IndexSettings.ToTemplateParameters()), EnableDefaultFiles = true, // serve index.html at /{options.RoutePrefix}/ }; fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider(); app.UseFileServer(fileServerOptions); return app; } } } ```
795f4095-9560-4ad2-baef-10c048503439
{ "language": "C#" }
```c# // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class MarkedString { public string Language { get; set; } public string Value { get; set; } } public class Hover { public MarkedString[] Contents { get; set; } public Range? Range { get; set; } } public class HoverRequest { public static readonly RequestType<TextDocumentPositionParams, Hover, object, object> Type = RequestType<TextDocumentPositionParams, Hover, object, object>.Create("textDocument/hover"); } } ``` Add registration options for hover request
```c# // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class MarkedString { public string Language { get; set; } public string Value { get; set; } } public class Hover { public MarkedString[] Contents { get; set; } public Range? Range { get; set; } } public class HoverRequest { public static readonly RequestType<TextDocumentPositionParams, Hover, object, TextDocumentRegistrationOptions> Type = RequestType<TextDocumentPositionParams, Hover, object, TextDocumentRegistrationOptions>.Create("textDocument/hover"); } } ```
b1d300dd-71cc-4eeb-acf8-d494a5d7e071
{ "language": "C#" }
```c# //#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0 var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); // Define directories. var buildDir = Directory("./src/Example/bin") + Directory(configuration); Task("Clean") .Does(() => { CleanDirectory(buildDir); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore("./Live.Forms.iOS.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { if(IsRunningOnWindows()) { // Use MSBuild MSBuild("./Live.Forms.iOS.sln", settings => settings.SetConfiguration(configuration)); } else { // Use XBuild XBuild("./Live.Forms.iOS.sln", settings => settings.SetConfiguration(configuration)); } }); Task("Default") .IsDependentOn("Build"); RunTarget(target);``` Build Script - cleanup and filling out vars
```c# //#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0 string target = Argument("target", "Default"); string configuration = Argument("configuration", "Release"); // Define directories. var dirs = new[] { Directory("./Live.Forms/bin") + Directory(configuration), Directory("./Live.Forms.iOS/bin") + Directory(configuration), }; string sln = "./Live.Forms.iOS.sln"; Task("Clean") .Does(() => { foreach (var dir in dirs) CleanDirectory(dir); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(sln); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { if(IsRunningOnWindows()) { // Use MSBuild MSBuild(sln, settings => settings .WithProperty("Platform", new[] { "iPhoneSimulator" }) .SetConfiguration(configuration)); } else { // Use XBuild XBuild(sln, settings => settings .WithProperty("Platform", new[] { "iPhoneSimulator" }) .SetConfiguration(configuration)); } }); Task("Default") .IsDependentOn("Build"); RunTarget(target);```
30ccc076-1a37-4eae-a744-623f8dcdde7c
{ "language": "C#" }
```c# using System.Data.Entity; using Kandanda.Dal.DataTransferObjects; namespace Kandanda.Dal { public class KandandaDbContext : DbContext { public KandandaDbContext() { Database.SetInitializer(new SampleDataDbInitializer()); } public DbSet<Tournament> Tournaments { get; set; } public DbSet<Participant> Participants { get; set; } public DbSet<Match> Matches { get; set; } public DbSet<Place> Places { get; set; } public DbSet<Phase> Phases { get; set; } public DbSet<TournamentParticipant> TournamentParticipants { get; set; } } }``` Fix tests, but not seeding Database anymore
```c# using System.Data.Entity; using Kandanda.Dal.DataTransferObjects; namespace Kandanda.Dal { public class KandandaDbContext : DbContext { public KandandaDbContext() { // TODO fix SetInitializer for tests Database.SetInitializer(new DropCreateDatabaseAlways<KandandaDbContext>()); } public DbSet<Tournament> Tournaments { get; set; } public DbSet<Participant> Participants { get; set; } public DbSet<Match> Matches { get; set; } public DbSet<Place> Places { get; set; } public DbSet<Phase> Phases { get; set; } public DbSet<TournamentParticipant> TournamentParticipants { get; set; } } }```
8d2d4166-e672-4001-bb49-3d018e843546
{ "language": "C#" }
```c#  namespace nuPickers.Shared.DotNetDataSource { using nuPickers.Shared.Editor; using System; using System.Reflection; using System.Collections.Generic; using System.Linq; public class DotNetDataSource { public string AssemblyName { get; set; } public string ClassName { get; set; } public IEnumerable<DotNetDataSourceProperty> Properties { get; set; } public IEnumerable<EditorDataItem> GetEditorDataItems() { List<EditorDataItem> editorDataItems = new List<EditorDataItem>(); object dotNetDataSource = Activator.CreateInstance(this.AssemblyName, this.ClassName).Unwrap(); foreach (PropertyInfo propertyInfo in dotNetDataSource.GetType().GetProperties().Where(x => this.Properties.Select(y => y.Name).Contains(x.Name))) { if (propertyInfo.PropertyType == typeof(string)) { propertyInfo.SetValue(dotNetDataSource, this.Properties.Where(x => x.Name == propertyInfo.Name).Single().Value); } else { // TODO: log unexpected property type } } return ((IDotNetDataSource)dotNetDataSource) .GetEditorDataItems() .Select(x => new EditorDataItem() { Key = x.Key, Label = x.Value }); } } } ``` Use Helper to create instance from assembly
```c#  namespace nuPickers.Shared.DotNetDataSource { using nuPickers.Shared.Editor; using System; using System.Reflection; using System.Collections.Generic; using System.Linq; public class DotNetDataSource { public string AssemblyName { get; set; } public string ClassName { get; set; } public IEnumerable<DotNetDataSourceProperty> Properties { get; set; } public IEnumerable<EditorDataItem> GetEditorDataItems() { List<EditorDataItem> editorDataItems = new List<EditorDataItem>(); object dotNetDataSource = Helper.GetAssembly(this.AssemblyName).CreateInstance(this.ClassName); foreach (PropertyInfo propertyInfo in dotNetDataSource.GetType().GetProperties().Where(x => this.Properties.Select(y => y.Name).Contains(x.Name))) { if (propertyInfo.PropertyType == typeof(string)) { propertyInfo.SetValue(dotNetDataSource, this.Properties.Where(x => x.Name == propertyInfo.Name).Single().Value); } else { // TODO: log unexpected property type } } return ((IDotNetDataSource)dotNetDataSource) .GetEditorDataItems() .Select(x => new EditorDataItem() { Key = x.Key, Label = x.Value }); } } } ```
04aa6e74-a1fe-4012-b163-09910f5deb08
{ "language": "C#" }
```c# namespace Certify.Models.Shared { public class RenewalStatusReport { public string InstanceId { get; set; } public string MachineName { get; set; } public ManagedSite ManagedSite { get; set; } public string PrimaryContactEmail { get; set; } public string AppVersion { get; set; } } }``` Add date to status report
```c# using System; namespace Certify.Models.Shared { public class RenewalStatusReport { public string InstanceId { get; set; } public string MachineName { get; set; } public ManagedSite ManagedSite { get; set; } public string PrimaryContactEmail { get; set; } public string AppVersion { get; set; } public DateTime? DateReported { get; set; } } }```
306f7f9d-b1bf-4b12-97b4-742316b96337
{ "language": "C#" }
```c# using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.Types.Responses { public sealed class GetDraftApprenticeshipResponse { public long Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Uln { get; set; } public string CourseCode { get; set; } public DeliveryModel DeliveryModel { get; set; } public string TrainingCourseName { get; set; } public string TrainingCourseVersion { get; set; } public string TrainingCourseOption { get; set; } public bool TrainingCourseVersionConfirmed { get; set; } public string StandardUId { get; set; } public int? Cost { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public DateTime? DateOfBirth { get; set; } public string Reference { get; set; } public Guid? ReservationId { get; set; } public bool IsContinuation { get; set; } public DateTime? OriginalStartDate { get; set; } public bool HasStandardOptions { get; set; } public int? EmploymentPrice { get; set; } public DateTime? EmploymentEndDate { get; set; } } } ``` Add `HasPriorLearning` to draft response
```c# using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.Types.Responses { public sealed class GetDraftApprenticeshipResponse { public long Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Uln { get; set; } public string CourseCode { get; set; } public DeliveryModel DeliveryModel { get; set; } public string TrainingCourseName { get; set; } public string TrainingCourseVersion { get; set; } public string TrainingCourseOption { get; set; } public bool TrainingCourseVersionConfirmed { get; set; } public string StandardUId { get; set; } public int? Cost { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public DateTime? DateOfBirth { get; set; } public string Reference { get; set; } public Guid? ReservationId { get; set; } public bool IsContinuation { get; set; } public DateTime? OriginalStartDate { get; set; } public bool HasStandardOptions { get; set; } public int? EmploymentPrice { get; set; } public DateTime? EmploymentEndDate { get; set; } public bool? HasPriorLearning { get; set; } } } ```
d775cffa-c574-44f2-b7e5-0e5291af99b4
{ "language": "C#" }
```c# using Autofac; using Autofac.Integration.WebApi; using FortuneTellerService4.Models; using Pivotal.Discovery.Client; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; using System.Web.Routing; namespace FortuneTellerService4 { public class WebApiApplication : System.Web.HttpApplication { private IDiscoveryClient _client; protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var config = GlobalConfiguration.Configuration; // Build application configuration ServerConfig.RegisterConfig("development"); // Create IOC container builder var builder = new ContainerBuilder(); // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register IDiscoveryClient, etc. builder.RegisterDiscoveryClient(ServerConfig.Configuration); // Initialize and Register FortuneContext builder.RegisterInstance(SampleData.InitializeFortunes()).SingleInstance(); // Register FortuneRepository builder.RegisterType<FortuneRepository>().As<IFortuneRepository>().SingleInstance(); var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // Start the Discovery client background thread _client = container.Resolve<IDiscoveryClient>(); } } } ``` Fix FortuneTeller for .NET4 not unregistering from eureka on app shutdown
```c# using Autofac; using Autofac.Integration.WebApi; using FortuneTellerService4.Models; using Pivotal.Discovery.Client; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; using System.Web.Routing; namespace FortuneTellerService4 { public class WebApiApplication : System.Web.HttpApplication { private IDiscoveryClient _client; protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var config = GlobalConfiguration.Configuration; // Build application configuration ServerConfig.RegisterConfig("development"); // Create IOC container builder var builder = new ContainerBuilder(); // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register IDiscoveryClient, etc. builder.RegisterDiscoveryClient(ServerConfig.Configuration); // Initialize and Register FortuneContext builder.RegisterInstance(SampleData.InitializeFortunes()).SingleInstance(); // Register FortuneRepository builder.RegisterType<FortuneRepository>().As<IFortuneRepository>().SingleInstance(); var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // Start the Discovery client background thread _client = container.Resolve<IDiscoveryClient>(); } protected void Application_End() { // Unregister current app with Service Discovery server _client.ShutdownAsync(); } } } ```
79a6f844-bd6e-4b15-bf61-98f1eed9c0d4
{ "language": "C#" }
```c# using System; using Xunit; namespace Stunts.Tests { public class StuntNamingTests { [Theory] [InlineData("StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] public void GetNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetName(baseType, implementedInterfaces)); [Theory] [InlineData(StuntNaming.DefaultNamespace + ".StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] public void GetFullNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetFullName(baseType, implementedInterfaces)); } } ``` Add extra test for generic type for naming
```c# using System; using System.Collections.Generic; using Xunit; namespace Stunts.Tests { public class StuntNamingTests { [Theory] [InlineData("StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] [InlineData("IEnumerableOfIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(IEnumerable<IDisposable>), typeof(IServiceProvider))] public void GetNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetName(baseType, implementedInterfaces)); [Theory] [InlineData(StuntNaming.DefaultNamespace + ".StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] [InlineData(StuntNaming.DefaultNamespace + ".IEnumerableOfIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(IEnumerable<IDisposable>), typeof(IServiceProvider))] public void GetFullNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetFullName(baseType, implementedInterfaces)); } } ```
6caf5381-d1db-454b-89f0-984c47432907
{ "language": "C#" }
```c# using System; using System.Diagnostics.Eventing.Reader; using System.Net; using System.Net.Http; using Cogito.Net.Http; using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Session; using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility; using Microsoft.Samples.Eventing; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Cogito.Tests.Net.Http { [TestClass] public class HttpMessageEventSourceTests { [TestMethod] public void Test_EventSource() { EventSourceAnalyzer.InspectAll(HttpMessageEventSource.Current); } [TestMethod] public void Test_Request() { using (var session = new TraceEventSession("MyRealTimeSession")) { session.Source.Dynamic.All += data => Console.WriteLine("GOT Event " + data); session.EnableProvider(TraceEventProviders.GetEventSourceGuidFromName("Cogito-Net-Http-Messages")); HttpMessageEventSource.Current.Request(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.tempuri.com")) { }); session.Source.Process(); } } [TestMethod] public void Test_Response() { HttpMessageEventSource.Current.Response(new HttpResponseMessage(HttpStatusCode.OK)); } } } ``` Disable broken test session thing.
```c# using System; using System.Diagnostics.Eventing.Reader; using System.Net; using System.Net.Http; using Cogito.Net.Http; using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Session; using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility; using Microsoft.Samples.Eventing; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Cogito.Tests.Net.Http { [TestClass] public class HttpMessageEventSourceTests { [TestMethod] public void Test_EventSource() { EventSourceAnalyzer.InspectAll(HttpMessageEventSource.Current); } //[TestMethod] //public void Test_Request() //{ // using (var session = new TraceEventSession("MyRealTimeSession")) // { // session.Source.Dynamic.All += data => Console.WriteLine("GOT Event " + data); // session.EnableProvider(TraceEventProviders.GetEventSourceGuidFromName("Cogito-Net-Http-Messages")); // HttpMessageEventSource.Current.Request(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.tempuri.com")) // { // }); // session.Source.Process(); // } //} //[TestMethod] //public void Test_Response() //{ // HttpMessageEventSource.Current.Response(new HttpResponseMessage(HttpStatusCode.OK)); //} } } ```
e747145e-2d95-4579-87c1-2368cb69f167
{ "language": "C#" }
```c# #region Using using System.Collections.Generic; using System.Windows.Input; using PuppyFramework.Services; #endregion namespace PuppyFramework.MenuService { public class MenuItem : MenuItemBase { #region Fields private ObservableSortedList<MenuItemBase> _children; private string _title; #endregion #region Properties public object CommandParamter { get; set; } public CommandBinding CommandBinding { get; set; } public ObservableSortedList<MenuItemBase> Children { get { return _children; } private set { SetProperty(ref _children, value); } } public string Title { get { return _title; } protected set { SetProperty(ref _title, value); } } #endregion #region Constructors public MenuItem(string title, double weight) : base(weight) { Title = title; Children = new ObservableSortedList<MenuItemBase>(); HiddenFlag = false; } #endregion #region Methods public void AddChild(MenuItemBase child, IComparer<MenuItemBase> menuItemComparer = null) { Children.Add(child); if (menuItemComparer != null) { Children.Sort(menuItemComparer); } } public bool RemoveChild(MenuItemBase child) { return Children.Remove(child); } #endregion } } ``` Fix bug - command parameter is always null.
```c# #region Using using System.Collections.Generic; using System.Windows.Input; using PuppyFramework.Services; #endregion namespace PuppyFramework.MenuService { public class MenuItem : MenuItemBase { #region Fields private ObservableSortedList<MenuItemBase> _children; private string _title; #endregion #region Properties public object CommandParameter { get; set; } public CommandBinding CommandBinding { get; set; } public ObservableSortedList<MenuItemBase> Children { get { return _children; } private set { SetProperty(ref _children, value); } } public string Title { get { return _title; } protected set { SetProperty(ref _title, value); } } #endregion #region Constructors public MenuItem(string title, double weight) : base(weight) { Title = title; Children = new ObservableSortedList<MenuItemBase>(); HiddenFlag = false; } #endregion #region Methods public void AddChild(MenuItemBase child, IComparer<MenuItemBase> menuItemComparer = null) { Children.Add(child); if (menuItemComparer != null) { Children.Sort(menuItemComparer); } } public bool RemoveChild(MenuItemBase child) { return Children.Remove(child); } #endregion } } ```
23ddd8f1-4a5f-47f8-8a12-8928e5ce574e
{ "language": "C#" }
```c# using FluentEmail.Core.Interfaces; using FluentEmail.Smtp; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Net; using System.Net.Mail; namespace Microsoft.Extensions.DependencyInjection { public static class FluentEmailSmtpBuilderExtensions { public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, SmtpClient smtpClient) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(smtpClient))); return builder; } public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port) => AddSmtpSender(builder, new SmtpClient(host, port)); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port, string username, string password) => AddSmtpSender(builder, new SmtpClient(host, port) { EnableSsl = true, Credentials = new NetworkCredential (username, password) }); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, Func<SmtpClient> clientFactory) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(clientFactory))); return builder; } } } ``` Fix AddSmtpSender extension methods to property add service
```c# using FluentEmail.Core.Interfaces; using FluentEmail.Smtp; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Net; using System.Net.Mail; namespace Microsoft.Extensions.DependencyInjection { public static class FluentEmailSmtpBuilderExtensions { public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, SmtpClient smtpClient) { builder.Services.TryAdd(ServiceDescriptor.Singleton<ISender>(x => new SmtpSender(smtpClient))); return builder; } public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port) => AddSmtpSender(builder, () => new SmtpClient(host, port)); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port, string username, string password) => AddSmtpSender(builder, () => new SmtpClient(host, port) { EnableSsl = true, Credentials = new NetworkCredential (username, password) }); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, Func<SmtpClient> clientFactory) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(clientFactory))); return builder; } } } ```
9ac803ca-a7b8-41ef-895d-c5d07874b304
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using MirrorSharp.Advanced; using SharpLab.Server.Common; namespace SharpLab.Server.MirrorSharp { [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public class SetOptionsFromClient : ISetOptionsFromClientExtension { private const string Optimize = "x-optimize"; private const string Target = "x-target"; private readonly IDictionary<string, ILanguageAdapter> _languages; public SetOptionsFromClient(IReadOnlyList<ILanguageAdapter> languages) { _languages = languages.ToDictionary(l => l.LanguageName); } public bool TrySetOption(IWorkSession session, string name, string value) { switch (name) { case Optimize: _languages[session.LanguageName].SetOptimize(session, value); return true; case Target: session.SetTargetName(value); _languages[session.LanguageName].SetOptionsForTarget(session, value); return true; default: return false; } } } }``` Fix x-container-experiment-seed failure in .NET Framework branches
```c# using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using MirrorSharp.Advanced; using SharpLab.Server.Common; namespace SharpLab.Server.MirrorSharp { [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public class SetOptionsFromClient : ISetOptionsFromClientExtension { private const string Optimize = "x-optimize"; private const string Target = "x-target"; private const string ContainerExperimentSeed = "x-container-experiment-seed"; private readonly IDictionary<string, ILanguageAdapter> _languages; public SetOptionsFromClient(IReadOnlyList<ILanguageAdapter> languages) { _languages = languages.ToDictionary(l => l.LanguageName); } public bool TrySetOption(IWorkSession session, string name, string value) { switch (name) { case Optimize: _languages[session.LanguageName].SetOptimize(session, value); return true; case Target: session.SetTargetName(value); _languages[session.LanguageName].SetOptionsForTarget(session, value); return true; case ContainerExperimentSeed: // not supported in .NET Framework return true; default: return false; } } } }```
c8859779-e54d-4a32-9eb1-26661935868c
{ "language": "C#" }
```c# <div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> comes into effect 3 April, 2017 </p> </div> </div> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> Positions Vacant </h1> <p> ACA would like your help! <a href="/position-vacant">Positions Vacant</a> </p> </div> </div> </div>``` Remove 'Positions Vacant' sticky note
```c# <div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> comes into effect 3 April, 2017 </p> </div> </div> </div>```
8a792086-834e-4090-9210-c8123fa6a3d6
{ "language": "C#" }
```c# using System; namespace GitIStage { internal sealed class ConsoleCommand { private readonly Action _handler; private readonly ConsoleKey _key; public readonly string Description; private readonly ConsoleModifiers _modifiers; public ConsoleCommand(Action handler, ConsoleKey key, string description) { _handler = handler; _key = key; Description = description; _modifiers = 0; } public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description) { _handler = handler; _key = key; _modifiers = modifiers; Description = description; } public void Execute() { _handler(); } public bool MatchesKey(ConsoleKeyInfo keyInfo) { return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers; } public string GetCommandShortcut() { string key = _key.ToString().Replace("Arrow", ""); if (_modifiers != 0) { return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}"; } else return key.ToString(); } } } ``` Fix showing digits - show '1' instead of 'D1'
```c# using System; namespace GitIStage { internal sealed class ConsoleCommand { private readonly Action _handler; private readonly ConsoleKey _key; public readonly string Description; private readonly ConsoleModifiers _modifiers; public ConsoleCommand(Action handler, ConsoleKey key, string description) { _handler = handler; _key = key; Description = description; _modifiers = 0; } public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description) { _handler = handler; _key = key; _modifiers = modifiers; Description = description; } public void Execute() { _handler(); } public bool MatchesKey(ConsoleKeyInfo keyInfo) { return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers; } public string GetCommandShortcut() { string key = _key.ToString().Replace("Arrow", ""); if (key.StartsWith("D") && key.Length == 2) key = key.Replace("D", ""); if (_modifiers != 0) return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}"; else return key.ToString(); } } } ```
fe9d9c01-2b78-4b37-b696-f15a3375360a
{ "language": "C#" }
```c# using Hyperledger.Indy.PoolApi; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Threading.Tasks; namespace Hyperledger.Indy.Test.PoolTests { [TestClass] public class CreatePoolTest : IndyIntegrationTestBase { [TestMethod] public async Task TestCreatePoolWorksForNullConfig() { var file = File.Create("testCreatePoolWorks.txn"); PoolUtils.WriteTransactions(file, 1); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", null); } [TestMethod] public async Task TestCreatePoolWorksForConfigJSON() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", configJson); } [TestMethod] public async Task TestCreatePoolWorksForTwice() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("pool1", configJson); var ex = await Assert.ThrowsExceptionAsync<PoolLedgerConfigExistsException>(() => Pool.CreatePoolLedgerConfigAsync("pool1", configJson) );; } } } ``` Create Pool Tests work. removed obsolete tests
```c# using Hyperledger.Indy.PoolApi; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Threading.Tasks; namespace Hyperledger.Indy.Test.PoolTests { [TestClass] public class CreatePoolTest : IndyIntegrationTestBase { [TestMethod] public async Task TestCreatePoolWorksForNullConfig() { string poolConfigName = "testCreatePoolWorks"; var file = File.Create(string.Format("{0}.txn", poolConfigName)); PoolUtils.WriteTransactions(file, 1); await Pool.CreatePoolLedgerConfigAsync(poolConfigName, null); } [TestMethod] public async Task TestCreatePoolWorksForConfigJSON() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", configJson); } [TestMethod] public async Task TestCreatePoolWorksForTwice() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("pool1", configJson); var ex = await Assert.ThrowsExceptionAsync<PoolLedgerConfigExistsException>(() => Pool.CreatePoolLedgerConfigAsync("pool1", configJson) );; } } } ```
8f909d9f-a418-4360-b5ad-115ea2468e8b
{ "language": "C#" }
```c# using Auth0.Core.Serialization; using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; namespace Auth0.Core { /// <summary> /// Error information captured from a failed API request. /// </summary> [JsonConverter(typeof(ApiErrorConverter))] public class ApiError { /// <summary> /// Description of the failing HTTP Status Code. /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Error code returned by the API. /// </summary> [JsonProperty("errorCode")] public string ErrorCode { get; set; } /// <summary> /// Description of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } /// <summary> /// Parse a <see cref="HttpResponseMessage"/> into an <see cref="ApiError"/> asynchronously. /// </summary> /// <param name="response"><see cref="HttpResponseMessage"/> to parse.</param> /// <returns><see cref="Task"/> representing the operation and associated <see cref="ApiError"/> on /// successful completion.</returns> public static async Task<ApiError> Parse(HttpResponseMessage response) { if (response == null || response.Content == null) return null; var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (String.IsNullOrEmpty(content)) return null; try { return JsonConvert.DeserializeObject<ApiError>(content); } catch (JsonSerializationException) { return new ApiError { Error = content, Message = content }; } } } }``` Handle other kinds of deserialization exceptions
```c# using Auth0.Core.Serialization; using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; namespace Auth0.Core { /// <summary> /// Error information captured from a failed API request. /// </summary> [JsonConverter(typeof(ApiErrorConverter))] public class ApiError { /// <summary> /// Description of the failing HTTP Status Code. /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Error code returned by the API. /// </summary> [JsonProperty("errorCode")] public string ErrorCode { get; set; } /// <summary> /// Description of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } /// <summary> /// Parse a <see cref="HttpResponseMessage"/> into an <see cref="ApiError"/> asynchronously. /// </summary> /// <param name="response"><see cref="HttpResponseMessage"/> to parse.</param> /// <returns><see cref="Task"/> representing the operation and associated <see cref="ApiError"/> on /// successful completion.</returns> public static async Task<ApiError> Parse(HttpResponseMessage response) { if (response == null || response.Content == null) return null; var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (String.IsNullOrEmpty(content)) return null; try { return JsonConvert.DeserializeObject<ApiError>(content); } catch (JsonException) { return new ApiError { Error = content, Message = content }; } } } }```
47131883-f2f0-4512-8f95-6110d943f1f1
{ "language": "C#" }
```c# using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.MySql { public class MySqlQuoter : GenericQuoter { public override string OpenQuote { get { return "`"; } } public override string CloseQuote { get { return "`"; } } public override string QuoteValue(object value) { return base.QuoteValue(value).Replace(@"\", @"\\"); } public override string FromTimeSpan(System.TimeSpan value) { return System.String.Format("{0}{1}:{2}:{3}.{4}{0}" , ValueQuote , value.Hours + (value.Days * 24) , value.Minutes , value.Seconds , value.Milliseconds); } } } ``` Fix MySql do not support Milliseconds
```c# using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.MySql { public class MySqlQuoter : GenericQuoter { public override string OpenQuote { get { return "`"; } } public override string CloseQuote { get { return "`"; } } public override string QuoteValue(object value) { return base.QuoteValue(value).Replace(@"\", @"\\"); } public override string FromTimeSpan(System.TimeSpan value) { return System.String.Format("{0}{1:00}:{2:00}:{3:00}{0}" , ValueQuote , value.Hours + (value.Days * 24) , value.Minutes , value.Seconds); } } } ```
7a505d71-3a3e-4233-ae9c-89e4ab8d2847
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Schema; namespace Codge.Generator.Presentations.Xsd { public static class XmlSchemaExtensions { public static bool IsEmptyType(this XmlSchemaComplexType type) { return type.ContentModel == null && type.Attributes.Count == 0 && type.ContentType.ToString() == "Empty"; } public static IEnumerable<XmlSchemaEnumerationFacet> GetEnumerationFacets(this XmlSchemaSimpleType simpleType) { if (simpleType.Content != null) { var restriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; if (restriction != null && restriction.Facets != null && restriction.Facets.Count > 0) { foreach (var facet in restriction.Facets) { var item = facet as XmlSchemaEnumerationFacet; if (item == null) yield break; yield return item; } } } yield break; } public static bool IsEnumeration(this XmlSchemaSimpleType simpleType) { return GetEnumerationFacets(simpleType).Any(); } } } ``` Fix for treating enum types as primitives due non-enumeration facets
```c# using System.Collections.Generic; using System.Linq; using System.Xml.Schema; namespace Codge.Generator.Presentations.Xsd { public static class XmlSchemaExtensions { public static bool IsEmptyType(this XmlSchemaComplexType type) { return type.ContentModel == null && type.Attributes.Count == 0 && type.ContentType.ToString() == "Empty"; } public static IEnumerable<XmlSchemaEnumerationFacet> GetEnumerationFacets(this XmlSchemaSimpleType simpleType) { if (simpleType.Content != null) { var restriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; if (restriction != null && restriction.Facets != null && restriction.Facets.Count > 0) { foreach (var facet in restriction.Facets) { var item = facet as XmlSchemaEnumerationFacet; if (item != null) yield return item; } } } yield break; } public static bool IsEnumeration(this XmlSchemaSimpleType simpleType) { return GetEnumerationFacets(simpleType).Any(); } } } ```
85d41e10-edaf-46cc-a441-289b6e156291
{ "language": "C#" }
```c# @model ICollection<AuthenticationClientData> @if (Model.Count > 0) { using (Html.BeginForm("ExternalLogin", "Account", new { ReturnUrl = ViewBag.ReturnUrl })) { @Html.AntiForgeryToken() <h4>Use another service to log in.</h4> <hr /> <div id="socialLoginList"> @foreach (AuthenticationClientData p in Model) { <button type="submit" class="btn" id="@p.AuthenticationClient.ProviderName" name="provider" value="@p.AuthenticationClient.ProviderName" title="Log in using your @p.DisplayName account">@p.DisplayName</button> } </div> } } ``` Fix external logins partial for running in mono 3.2.x
```c# @model ICollection<Microsoft.Web.WebPages.OAuth.AuthenticationClientData> @if (Model.Count > 0) { using (Html.BeginForm("ExternalLogin", "Account", new { ReturnUrl = ViewBag.ReturnUrl })) { @Html.AntiForgeryToken() <h4>Use another service to log in.</h4> <hr /> <div id="socialLoginList"> @foreach (var p in Model) { <button type="submit" class="btn" id="@p.AuthenticationClient.ProviderName" name="provider" value="@p.AuthenticationClient.ProviderName" title="Log in using your @p.DisplayName account">@p.DisplayName</button> } </div> } } ```
a176d67e-cf93-427b-bb8f-f4c0f74fa1ef
{ "language": "C#" }
```c# using System; using Eto.Drawing; using Eto.Forms; using MonoMac.AppKit; using SD = System.Drawing; namespace Eto.Platform.Mac.Forms { public class FormHandler : MacWindow<MyWindow, Form>, IDisposable, IForm { protected override bool DisposeControl { get { return false; } } public FormHandler() { Control = new MyWindow(new SD.Rectangle(0,0,200,200), NSWindowStyle.Resizable | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable | NSWindowStyle.Titled, NSBackingStore.Buffered, false); ConfigureWindow (); } public void Show () { if (!Control.IsVisible) Widget.OnShown (EventArgs.Empty); if (this.WindowState == WindowState.Minimized) Control.MakeKeyWindow (); else Control.MakeKeyAndOrderFront (ApplicationHandler.Instance.AppDelegate); } } } ``` Call Form.OnShown after window is shown (to be consistent with dialog)
```c# using System; using Eto.Forms; using MonoMac.AppKit; using SD = System.Drawing; namespace Eto.Platform.Mac.Forms { public class FormHandler : MacWindow<MyWindow, Form>, IForm { protected override bool DisposeControl { get { return false; } } public FormHandler() { Control = new MyWindow(new SD.Rectangle(0, 0, 200, 200), NSWindowStyle.Resizable | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable | NSWindowStyle.Titled, NSBackingStore.Buffered, false); ConfigureWindow(); } public void Show() { if (WindowState == WindowState.Minimized) Control.MakeKeyWindow(); else Control.MakeKeyAndOrderFront(ApplicationHandler.Instance.AppDelegate); if (!Control.IsVisible) Widget.OnShown(EventArgs.Empty); } } } ```
c76992fd-bc3d-4680-abb3-378d2abc3f0b
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class TestSceneOsuModAimAssist : OsuModTestScene { [Test] public void TestAimAssist() { var mod = new OsuModAimAssist(); CreateModTest(new ModTestData { Autoplay = false, Mod = mod, }); } } } ``` Add testing of different strengths
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class TestSceneOsuModAimAssist : OsuModTestScene { [TestCase(0.1f)] [TestCase(0.5f)] [TestCase(1)] public void TestAimAssist(float strength) { CreateModTest(new ModTestData { Mod = new OsuModAimAssist { AssistStrength = { Value = strength }, }, PassCondition = () => true, Autoplay = false, }); } } } ```
b5efadd6-693a-4d17-9d1d-13524107d61e
{ "language": "C#" }
```c# using davClassLibrary.Common; using davClassLibrary.DataAccess; using UniversalSoundBoard.DataAccess; using Windows.Networking.Connectivity; namespace UniversalSoundboard.Common { public class GeneralMethods : IGeneralMethods { public bool IsNetworkAvailable() { var connection = NetworkInformation.GetInternetConnectionProfile(); var networkCostType = connection.GetConnectionCost().NetworkCostType; return !(networkCostType != NetworkCostType.Unrestricted && networkCostType != NetworkCostType.Unknown); } public DavEnvironment GetEnvironment() { return FileManager.Environment; } } } ``` Check for null in IsNetworkAvailable implementation
```c# using davClassLibrary.Common; using davClassLibrary.DataAccess; using UniversalSoundBoard.DataAccess; using Windows.Networking.Connectivity; namespace UniversalSoundboard.Common { public class GeneralMethods : IGeneralMethods { public bool IsNetworkAvailable() { var connection = NetworkInformation.GetInternetConnectionProfile(); if (connection == null) return false; var networkCostType = connection.GetConnectionCost().NetworkCostType; return !(networkCostType != NetworkCostType.Unrestricted && networkCostType != NetworkCostType.Unknown); } public DavEnvironment GetEnvironment() { return FileManager.Environment; } } } ```
b2150d8f-3a19-4516-aa4e-7f6007da9a33
{ "language": "C#" }
```c# using JoinRpg.Web.CheckIn; using JoinRpg.Web.ProjectCommon; using JoinRpg.Web.ProjectMasterTools.ResponsibleMaster; using JoinRpg.Web.ProjectMasterTools.Subscribe; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; namespace JoinRpg.Blazor.Client.ApiClients; public static class HttpClientRegistration { private static WebAssemblyHostBuilder AddHttpClient<TClient, TImplementation>( this WebAssemblyHostBuilder builder) where TClient : class where TImplementation : class, TClient { _ = builder.Services.AddHttpClient<TClient, TImplementation>( client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)); return builder; } public static WebAssemblyHostBuilder AddHttpClients(this WebAssemblyHostBuilder builder) { return builder .AddHttpClient<IGameSubscribeClient, GameSubscribeClient>() .AddHttpClient<ICharacterGroupsClient, CharacterGroupsClient>() .AddHttpClient<ICheckInClient, CheckInClient>() .AddHttpClient<IResponsibleMasterRuleClient, ApiClients.ResponsibleMasterRuleClient>(); } } ``` Fix namespace in httpclient registration
```c# using JoinRpg.Web.CheckIn; using JoinRpg.Web.ProjectCommon; using JoinRpg.Web.ProjectMasterTools.ResponsibleMaster; using JoinRpg.Web.ProjectMasterTools.Subscribe; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; namespace JoinRpg.Blazor.Client.ApiClients; public static class HttpClientRegistration { private static WebAssemblyHostBuilder AddHttpClient<TClient, TImplementation>( this WebAssemblyHostBuilder builder) where TClient : class where TImplementation : class, TClient { _ = builder.Services.AddHttpClient<TClient, TImplementation>( client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)); return builder; } public static WebAssemblyHostBuilder AddHttpClients(this WebAssemblyHostBuilder builder) { return builder .AddHttpClient<IGameSubscribeClient, GameSubscribeClient>() .AddHttpClient<ICharacterGroupsClient, CharacterGroupsClient>() .AddHttpClient<ICheckInClient, CheckInClient>() .AddHttpClient<IResponsibleMasterRuleClient, ResponsibleMasterRuleClient>(); } } ```
615b281f-64a4-4850-ac2a-5a684fb05caf
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Platform; namespace osu.Game.Screens.Play { internal class ScreenSuspensionHandler : Component { private readonly GameplayClockContainer gameplayClockContainer; private Bindable<bool> isPaused; [Resolved] private GameHost host { get; set; } public ScreenSuspensionHandler(GameplayClockContainer gameplayClockContainer) { this.gameplayClockContainer = gameplayClockContainer; } protected override void LoadComplete() { base.LoadComplete(); isPaused = gameplayClockContainer.IsPaused.GetBoundCopy(); isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); isPaused?.UnbindAll(); if (host != null) host.AllowScreenSuspension.Value = true; } } } ``` Add null check and xmldoc
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Platform; namespace osu.Game.Screens.Play { /// <summary> /// Ensures screen is not suspended / dimmed while gameplay is active. /// </summary> public class ScreenSuspensionHandler : Component { private readonly GameplayClockContainer gameplayClockContainer; private Bindable<bool> isPaused; [Resolved] private GameHost host { get; set; } public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer) { this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer)); } protected override void LoadComplete() { base.LoadComplete(); isPaused = gameplayClockContainer.IsPaused.GetBoundCopy(); isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); isPaused?.UnbindAll(); if (host != null) host.AllowScreenSuspension.Value = true; } } } ```
66aff45b-df25-47c8-aa3f-bc11a617a8f6
{ "language": "C#" }
```c# using System; using System.Threading; namespace Bumblebee.Extensions { public static class Debugging { public static T DebugPrint<T>(this T obj) { Console.WriteLine(obj.ToString()); return obj; } public static T DebugPrint<T>(this T obj, string message) { Console.WriteLine(message); return obj; } public static T DebugPrint<T>(this T obj, Func<T, object> func) { Console.WriteLine(func.Invoke(obj)); return obj; } public static T Pause<T>(this T block, int seconds) { if (seconds > 0) Thread.Sleep(1000 * seconds); return block; } } }``` Add PlaySound as a debugging 'tool'
```c# using System; using System.Threading; namespace Bumblebee.Extensions { public static class Debugging { public static T DebugPrint<T>(this T obj) { Console.WriteLine(obj.ToString()); return obj; } public static T DebugPrint<T>(this T obj, string message) { Console.WriteLine(message); return obj; } public static T DebugPrint<T>(this T obj, Func<T, object> func) { Console.WriteLine(func.Invoke(obj)); return obj; } public static T PlaySound<T>(this T obj, int pause = 0) { System.Media.SystemSounds.Exclamation.Play(); return obj.Pause(pause); } public static T Pause<T>(this T block, int seconds) { if (seconds > 0) Thread.Sleep(1000 * seconds); return block; } } }```