Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Configure await false to remove deadlocks
using Microsoft.Azure.AppService.ApiApps.Service; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TRex.Extensions { public static class ClientTriggerCallbackExtensions { /// <summary> /// Invokes the callback while wrapping the result in a "body" object /// to go along with the default expression completion in the /// Logic App designer /// </summary> /// <param name="callback">Callback to invoke</param> /// <param name="runtime">Runtime settings</param> /// <param name="result">Result to push to the Logic App</param> public async static Task InvokeAsyncWithBody<TResult>( this ClientTriggerCallback<TResult> callback, Runtime runtime, TResult result) { // This is a hack, and it doesn't feel sound, but it works. JObject values = new JObject(); values.Add("body", JToken.FromObject(result)); await callback.InvokeAsync(runtime, values); } } }
using Microsoft.Azure.AppService.ApiApps.Service; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TRex.Extensions { public static class ClientTriggerCallbackExtensions { /// <summary> /// Invokes the callback while wrapping the result in a "body" object /// to go along with the default expression completion in the /// Logic App designer /// </summary> /// <param name="callback">Callback to invoke</param> /// <param name="runtime">Runtime settings</param> /// <param name="result">Result to push to the Logic App</param> public async static Task InvokeAsyncWithBody<TResult>( this ClientTriggerCallback<TResult> callback, Runtime runtime, TResult result) { // This is a hack, and it doesn't feel sound, but it works. JObject values = new JObject(); values.Add("body", JToken.FromObject(result)); await callback.InvokeAsync(runtime, values).ConfigureAwait(false); } } }
Write to log instead of console
using System; using EvilDICOM.Core.Enums; namespace EvilDICOM.Core.IO.Data { public class DataRestriction { public static string EnforceLengthRestriction(uint lengthLimit, string data) { if (data.Length > lengthLimit) { Console.Write( "Not DICOM compliant. Attempted data input of {0} characters. Data size is limited to {1} characters. Read anyway.", data.Length, lengthLimit); return data; } return data; } public static byte[] EnforceEvenLength(byte[] data, VR vr) { switch (vr) { case VR.UniqueIdentifier: case VR.OtherByteString: case VR.Unknown: return DataPadder.PadNull(data); case VR.AgeString: case VR.ApplicationEntity: case VR.CodeString: case VR.Date: case VR.DateTime: case VR.DecimalString: case VR.IntegerString: case VR.LongString: case VR.LongText: case VR.PersonName: case VR.ShortString: case VR.ShortText: case VR.Time: case VR.UnlimitedText: return DataPadder.PadSpace(data); default: return data; } } } }
using System; using EvilDICOM.Core.Enums; using EvilDICOM.Core.Logging; namespace EvilDICOM.Core.IO.Data { public class DataRestriction { public static string EnforceLengthRestriction(uint lengthLimit, string data) { if (data.Length > lengthLimit) { EvilLogger.Instance.Log( "Not DICOM compliant. Attempted data input of {0} characters. Data size is limited to {1} characters. Read anyway.", data.Length, lengthLimit); return data; } return data; } public static byte[] EnforceEvenLength(byte[] data, VR vr) { switch (vr) { case VR.UniqueIdentifier: case VR.OtherByteString: case VR.Unknown: return DataPadder.PadNull(data); case VR.AgeString: case VR.ApplicationEntity: case VR.CodeString: case VR.Date: case VR.DateTime: case VR.DecimalString: case VR.IntegerString: case VR.LongString: case VR.LongText: case VR.PersonName: case VR.ShortString: case VR.ShortText: case VR.Time: case VR.UnlimitedText: return DataPadder.PadSpace(data); default: return data; } } } }
Update Problems: 3 - 5
namespace StudentsTask { using System; using System.Collections.Generic; using System.Linq; public class Student { public const int MinAgeOfStudent = 6; private string firstName; private string lastName; private int age; public Student(string initialFirstName, string initialLastName, int initialAge) { this.FirstName = initialFirstName; this.LastName = initialLastName; this.Age = initialAge; } public string FirstName { get { return this.firstName; } private set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("First name cannot be null or empty."); } this.firstName = value; } } public string LastName { get { return this.lastName; } private set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("Last name cannot be null or empty."); } this.lastName = value; } } public int Age { get { return this.age; } set { if (value < Student.MinAgeOfStudent) { throw new ArgumentOutOfRangeException(string.Format("Student cannot be yonger than {0}", Student.MinAgeOfStudent)); } this.age = value; } } } }
// Problem 3. First before last // Write a method that from a given array of students finds all students whose first name is before its last name alphabetically. // Use LINQ query operators. // Problem 4. Age range // Write a LINQ query that finds the first name and last name of all students with age between 18 and 24. // Problem 5. Order students // Using the extension methods OrderBy() and ThenBy() with lambda expressions sort the students by first name and last name in descending order. // Rewrite the same with LINQ. namespace StudentsTask { using System; using System.Collections.Generic; using System.Linq; public class Student { public const int MinAgeOfStudent = 6; private string firstName; private string lastName; private int age; public Student(string initialFirstName, string initialLastName, int initialAge) { this.FirstName = initialFirstName; this.LastName = initialLastName; this.Age = initialAge; } public string FirstName { get { return this.firstName; } private set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("First name cannot be null or empty."); } this.firstName = value; } } public string LastName { get { return this.lastName; } private set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("Last name cannot be null or empty."); } this.lastName = value; } } public int Age { get { return this.age; } set { if (value < Student.MinAgeOfStudent) { throw new ArgumentOutOfRangeException(string.Format("Student cannot be yonger than {0}", Student.MinAgeOfStudent)); } this.age = value; } } } }
Update to support EF container isolation issue
using System.Diagnostics; using Glimpse.Agent; using Glimpse.Agent.Configuration; using Glimpse.Initialization; using Microsoft.Extensions.DependencyInjection; namespace Glimpse.Agent.Internal.Inspectors.Mvc { public class AgentStartupWebDiagnosticsInspector : IAgentStartup { public AgentStartupWebDiagnosticsInspector(IRequestIgnorerManager requestIgnorerManager) { RequestIgnorerManager = requestIgnorerManager; } private IRequestIgnorerManager RequestIgnorerManager { get; } public void Run(IStartupOptions options) { var appServices = options.ApplicationServices; var telemetryListener = appServices.GetRequiredService<DiagnosticListener>(); telemetryListener.SubscribeWithAdapter(appServices.GetRequiredService<WebDiagnosticsInspector>(), IsEnabled); } private bool IsEnabled(string topic) { return !RequestIgnorerManager.ShouldIgnore(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Glimpse.Agent; using Glimpse.Agent.Configuration; using Glimpse.Initialization; using Microsoft.Extensions.DependencyInjection; namespace Glimpse.Agent.Internal.Inspectors.Mvc { public class AgentStartupWebDiagnosticsInspector : IAgentStartup { public AgentStartupWebDiagnosticsInspector(IRequestIgnorerManager requestIgnorerManager) { RequestIgnorerManager = requestIgnorerManager; } private IRequestIgnorerManager RequestIgnorerManager { get; } public void Run(IStartupOptions options) { var appServices = options.ApplicationServices; //var telemetryListener = appServices.GetRequiredService<DiagnosticListener>(); //telemetryListener.SubscribeWithAdapter(appServices.GetRequiredService<WebDiagnosticsInspector>(), IsEnabled); var listenerSubscription = DiagnosticListener.AllListeners.Subscribe(listener => { listener.SubscribeWithAdapter(appServices.GetRequiredService<WebDiagnosticsInspector>(), IsEnabled); }); } private bool IsEnabled(string topic) { return !RequestIgnorerManager.ShouldIgnore(); } } }
Make sure we always add our nop_api scope in order for the token to have access to the resources. Also make sure we always add offline_access scope as it is required by the IdentityServer. This way even if empty scope is passed i.e if using Postman the scope is empty, we still can obtain tokens with the correct scope. This is done so that we don't force all clients to specify the scope if they don't know it.
namespace Nop.Plugin.Api.IdentityServer.Middlewares { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Primitives; public class IdentityServerScopeParameterMiddleware { private readonly RequestDelegate _next; public IdentityServerScopeParameterMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { if (context.Request.Path.Value.Equals("/connect/authorize", StringComparison.InvariantCultureIgnoreCase) || context.Request.Path.Value.Equals("/oauth/authorize", StringComparison.InvariantCultureIgnoreCase)) { if (!context.Request.Query.ContainsKey("scope")) { var queryValues = new Dictionary<string, StringValues>(); foreach (var item in context.Request.Query) { queryValues.Add(item.Key, item.Value); } queryValues.Add("scope", "nop_api offline_access"); var newQueryCollection = new QueryCollection(queryValues); context.Request.Query = newQueryCollection; } } await _next(context); } } }
namespace Nop.Plugin.Api.IdentityServer.Middlewares { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Primitives; public class IdentityServerScopeParameterMiddleware { private readonly RequestDelegate _next; public IdentityServerScopeParameterMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { if (context.Request.Path.Value.Equals("/connect/authorize", StringComparison.InvariantCultureIgnoreCase) || context.Request.Path.Value.Equals("/oauth/authorize", StringComparison.InvariantCultureIgnoreCase)) { // Make sure we have "nop_api" and "offline_access" scope var queryValues = new Dictionary<string, StringValues>(); foreach (var item in context.Request.Query) { if (item.Key == "scope") { string scopeValue = item.Value; if (!scopeValue.Contains("nop_api offline_access")) { // add our scope instead since we don't support other scopes queryValues.Add(item.Key, "nop_api offline_access"); continue; } } queryValues.Add(item.Key, item.Value); } if (!queryValues.ContainsKey("scope")) { // if no scope is specified we add it queryValues.Add("scope", "nop_api offline_access"); } var newQueryCollection = new QueryCollection(queryValues); context.Request.Query = newQueryCollection; } await _next(context); } } }
Add support for followpoint skinning
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK; using OpenTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections { public class FollowPoint : Container { private const float width = 8; public override bool RemoveWhenNotAlive => false; public FollowPoint() { Origin = Anchor.Centre; Masking = true; AutoSizeAxes = Axes.Both; CornerRadius = width / 2; EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Glow, Colour = Color4.White.Opacity(0.2f), Radius = 4, }; Children = new Drawable[] { new Box { Size = new Vector2(width), Blending = BlendingMode.Additive, Origin = Anchor.Centre, Anchor = Anchor.Centre, Alpha = 0.5f, }, }; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK; using OpenTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections { public class FollowPoint : Container { private const float width = 8; public override bool RemoveWhenNotAlive => false; public FollowPoint() { Origin = Anchor.Centre; Child = new SkinnableDrawable("Play/osu/followpoint", _ => new Container { Masking = true, AutoSizeAxes = Axes.Both, CornerRadius = width / 2, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Glow, Colour = Color4.White.Opacity(0.2f), Radius = 4, }, Child = new Box { Size = new Vector2(width), Blending = BlendingMode.Additive, Origin = Anchor.Centre, Anchor = Anchor.Centre, } }, restrictSize: false) { Alpha = 0.5f, }; } } }
Fix consistent updating of layout fields if both sides have a significant, but blank value (e.g. certain core db items)
using System; using System.Xml; using System.Xml.Linq; using Rainbow.Model; namespace Rainbow.Diff.Fields { public class XmlComparison : FieldTypeBasedComparison { public override bool AreEqual(IItemFieldValue field1, IItemFieldValue field2) { if (string.IsNullOrWhiteSpace(field1.Value) || string.IsNullOrWhiteSpace(field2.Value)) return false; try { var x1 = XElement.Parse(field1.Value); var x2 = XElement.Parse(field2.Value); return XNode.DeepEquals(x1, x2); } catch (XmlException xe) { throw new InvalidOperationException($"Unable to compare {field1.NameHint ?? field2.NameHint} field due to invalid XML value.", xe); } } public override string[] SupportedFieldTypes => new[] { "Layout", "Tracking", "Rules" }; } }
using System; using System.Xml; using System.Xml.Linq; using Rainbow.Model; namespace Rainbow.Diff.Fields { public class XmlComparison : FieldTypeBasedComparison { public override bool AreEqual(IItemFieldValue field1, IItemFieldValue field2) { if (string.IsNullOrWhiteSpace(field1.Value) && string.IsNullOrWhiteSpace(field2.Value)) return true; if (string.IsNullOrWhiteSpace(field1.Value) || string.IsNullOrWhiteSpace(field2.Value)) return false; try { var x1 = XElement.Parse(field1.Value); var x2 = XElement.Parse(field2.Value); return XNode.DeepEquals(x1, x2); } catch (XmlException xe) { throw new InvalidOperationException($"Unable to compare {field1.NameHint ?? field2.NameHint} field due to invalid XML value.", xe); } } public override string[] SupportedFieldTypes => new[] { "Layout", "Tracking", "Rules" }; } }
Fix up the VB side
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Roslyn.VisualStudio.IntegrationTests.Extensions.Editor; using Roslyn.VisualStudio.IntegrationTests.Extensions.SolutionExplorer; using Xunit; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicGoToImplementation : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicGoToImplementation(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicGoToImplementation)) { } [Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)] public void SimpleGoToImplementation() { var project = new ProjectUtils.Project(ProjectName); this.AddFile("FileImplementation.vb", project); this.OpenFile("FileImplementation.vb", project); Editor.SetText( @"Class Implementation Implements IFoo End Class"); this.AddFile("FileInterface.vb", project); this.OpenFile("FileInterface.vb", project); Editor.SetText( @"Interface IFoo End Interface"); this.PlaceCaret("Interface IFoo"); Editor.GoToImplementation(); this.VerifyTextContains(@"Class Implementation$$", assertCaretPosition: true); Assert.False(VisualStudio.Instance.Shell.IsActiveTabProvisional()); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicGoToImplementation : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicGoToImplementation(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicGoToImplementation)) { } [Fact, Trait(Traits.Feature, Traits.Features.GoToImplementation)] public void SimpleGoToImplementation() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "FileImplementation.vb"); VisualStudio.SolutionExplorer.OpenFile(project, "FileImplementation.vb"); VisualStudio.Editor.SetText( @"Class Implementation Implements IFoo End Class"); VisualStudio.SolutionExplorer.AddFile(project, "FileInterface.vb"); VisualStudio.SolutionExplorer.OpenFile(project, "FileInterface.vb"); VisualStudio.Editor.SetText( @"Interface IFoo End Interface"); VisualStudio.Editor.PlaceCaret("Interface IFoo"); VisualStudio.Editor.GoToImplementation(); VisualStudio.Editor.Verify.TextContains(@"Class Implementation$$", assertCaretPosition: true); Assert.False(VisualStudio.Shell.IsActiveTabProvisional()); } } }
Fix for test from last commit.
using Microsoft.VisualStudio.TestTools.UnitTesting; using NJsonSchema.CodeGeneration.Tests.Models; using NJsonSchema.CodeGeneration.TypeScript; using NJsonSchema.Generation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NJsonSchema.CodeGeneration.Tests.TypeScript { [TestClass] public class NullabilityTests { [TestMethod] public async Task Strict_nullability_in_TypeScript2() { var schema = await JsonSchema4.FromTypeAsync<Person>( new JsonSchemaGeneratorSettings { DefaultReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull }); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeScriptVersion = 2 }); var output = generator.GenerateFile("MyClass"); Assert.IsTrue(output.Contains("timeSpan: string;")); Assert.IsTrue(output.Contains("gender: string;")); Assert.IsTrue(output.Contains("address: string;")); Assert.IsTrue(output.Contains("timeSpanOrNull: string | undefined;")); Assert.IsTrue(output.Contains("genderOrNull: string | undefined;")); Assert.IsTrue(output.Contains("addressOrNull: string | undefined;")); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using NJsonSchema.CodeGeneration.Tests.Models; using NJsonSchema.CodeGeneration.TypeScript; using NJsonSchema.Generation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NJsonSchema.CodeGeneration.Tests.TypeScript { [TestClass] public class NullabilityTests { [TestMethod] public async Task Strict_nullability_in_TypeScript2() { var schema = await JsonSchema4.FromTypeAsync<Person>( new JsonSchemaGeneratorSettings { DefaultReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull }); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeScriptVersion = 2 }); var output = generator.GenerateFile("MyClass"); Assert.IsTrue(output.Contains("timeSpan: string;")); Assert.IsTrue(output.Contains("gender: Gender;")); Assert.IsTrue(output.Contains("address: Address;")); Assert.IsTrue(output.Contains("timeSpanOrNull: string | undefined;")); Assert.IsTrue(output.Contains("genderOrNull: Gender | undefined;")); Assert.IsTrue(output.Contains("addressOrNull: Address | undefined;")); } } }
Set new manage Guid when ballots are created
using System.Data.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using VotingApplication.Data.Context; using VotingApplication.Data.Model; using VotingApplication.Web.Api.Filters; using VotingApplication.Web.Api.Models.DBViewModels; namespace VotingApplication.Web.Api.Controllers.API_Controllers { public class PollTokenController : WebApiController { public PollTokenController() : base() { } public PollTokenController(IContextFactory contextFactory) : base(contextFactory) { } #region GET public Guid Get(Guid pollId) { using (var context = _contextFactory.CreateContext()) { Poll poll = context.Polls.Where(s => s.UUID == pollId).Include(s => s.Options).SingleOrDefault(); if (poll == null) { ThrowError(HttpStatusCode.NotFound, string.Format("Poll {0} not found", pollId)); } if (poll.InviteOnly) { ThrowError(HttpStatusCode.Forbidden, string.Format("Poll {0} is invite only", pollId)); } Guid newTokenGuid = Guid.NewGuid(); if(poll.Ballots == null) { poll.Ballots = new List<Ballot>(); } poll.Ballots.Add(new Ballot { TokenGuid = newTokenGuid }); context.SaveChanges(); return newTokenGuid; } } #endregion } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Net; using VotingApplication.Data.Context; using VotingApplication.Data.Model; namespace VotingApplication.Web.Api.Controllers.API_Controllers { public class PollTokenController : WebApiController { public PollTokenController() : base() { } public PollTokenController(IContextFactory contextFactory) : base(contextFactory) { } #region GET public Guid Get(Guid pollId) { using (var context = _contextFactory.CreateContext()) { Poll poll = context.Polls.Where(s => s.UUID == pollId).Include(s => s.Options).SingleOrDefault(); if (poll == null) { ThrowError(HttpStatusCode.NotFound, string.Format("Poll {0} not found", pollId)); } if (poll.InviteOnly) { ThrowError(HttpStatusCode.Forbidden, string.Format("Poll {0} is invite only", pollId)); } Guid newTokenGuid = Guid.NewGuid(); if (poll.Ballots == null) { poll.Ballots = new List<Ballot>(); } poll.Ballots.Add(new Ballot { TokenGuid = newTokenGuid, ManageGuid = Guid.NewGuid() }); context.SaveChanges(); return newTokenGuid; } } #endregion } }
Update the sample application to retrieve the current time via SNTP
using System; using Microsoft.SPOT; using MicroTweet; using System.Net; using System.Threading; namespace SampleApplication { public class Program { public static void Main() { // Wait for DHCP while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) Thread.Sleep(50); // Set up application and user credentials // Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens var appCredentials = new OAuthApplicationCredentials() { ConsumerKey = "YOUR_CONSUMER_KEY_HERE", ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE", }; var userCredentials = new OAuthUserCredentials() { AccessToken = "YOUR_ACCESS_TOKEN", AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET", }; // Create new Twitter client with these credentials var twitter = new TwitterClient(appCredentials, userCredentials); // Send a tweet twitter.SendTweet("Trying out MicroTweet!"); } } }
using System; using Microsoft.SPOT; using MicroTweet; using System.Net; using System.Threading; namespace SampleApplication { public class Program { public static void Main() { // Wait for DHCP while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) Thread.Sleep(50); // Update the current time (since Twitter OAuth API requests require a valid timestamp) DateTime utcTime = Sntp.GetCurrentUtcTime(); Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime); // Set up application and user credentials // Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens var appCredentials = new OAuthApplicationCredentials() { ConsumerKey = "YOUR_CONSUMER_KEY_HERE", ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE", }; var userCredentials = new OAuthUserCredentials() { AccessToken = "YOUR_ACCESS_TOKEN", AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET", }; // Create new Twitter client with these credentials var twitter = new TwitterClient(appCredentials, userCredentials); // Send a tweet twitter.SendTweet("Trying out MicroTweet!"); } } }
Change repository version to "0.0.0-alpha". The version numbers are updated by the build script (appveyor.yml).
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("OxyPlot")] [assembly: AssemblyCompany("OxyPlot")] [assembly: AssemblyCopyright("Copyright (C) OxyPlot 2012.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2014.1.1.1")] [assembly: AssemblyInformationalVersion("2014.1.1.1-alpha")] [assembly: AssemblyFileVersion("2014.1.1.1")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("OxyPlot")] [assembly: AssemblyCompany("OxyPlot")] [assembly: AssemblyCopyright("Copyright (c) 2014 OxyPlot contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The version numbers are updated by the build script. See ~/appveyor.yml [assembly: AssemblyVersion("0.0.0")] [assembly: AssemblyInformationalVersion("0.0.0-alpha")] [assembly: AssemblyFileVersion("0.0.0")]
Fix compilation error within the unit test
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching { public partial class CSharpAsAndNullCheckTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task FixAllInDocument1() { await TestInRegularAndScriptAsync( @"class C { void M() { string a; {|FixAllInDocument:var|} x = o as string; if (x != null) { } var y = o as string; if (y != null) { } if ((a = o as string) != null) { } var c = o as string; var d = c != null ? 1 : 0; var e = o as string; return e != null ? 1 : 0; } }", @"class C { void M() { if (o is string x) { } if (o is string y) { } if (o is string a) { } var d = o is string c ? 1 : 0; return o is string e ? 1 : 0; } }"); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching { public partial class CSharpAsAndNullCheckTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task FixAllInDocument1() { await TestInRegularAndScriptAsync( @"class C { int M() { string a; {|FixAllInDocument:var|} x = o as string; if (x != null) { } var y = o as string; if (y != null) { } if ((a = o as string) != null) { } var c = o as string; var d = c != null ? 1 : 0; var e = o as string; return e != null ? 1 : 0; } }", @"class C { int M() { if (o is string x) { } if (o is string y) { } if (o is string a) { } var d = o is string c ? 1 : 0; return o is string e ? 1 : 0; } }"); } } }
Add support for MetadataChanged/ItemMetadataChanged (whichever it turns out to be)
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SyncTrayzor.SyncThing.ApiClient { [JsonConverter(typeof(StringEnumConverter))] public enum EventType { Starting, StartupComplete, Ping, DeviceDiscovered, DeviceConnected, DeviceDisconnected, RemoteIndexUpdated, LocalIndexUpdated, ItemStarted, ItemFinished, StateChanged, FolderRejected, DeviceRejected, ConfigSaved, DownloadProgress, FolderSummary, FolderCompletion, } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SyncTrayzor.SyncThing.ApiClient { [JsonConverter(typeof(StringEnumConverter))] public enum EventType { Starting, StartupComplete, Ping, DeviceDiscovered, DeviceConnected, DeviceDisconnected, RemoteIndexUpdated, LocalIndexUpdated, ItemStarted, ItemFinished, // Not quite sure which it's going to be, so play it safe... MetadataChanged, ItemMetadataChanged, StateChanged, FolderRejected, DeviceRejected, ConfigSaved, DownloadProgress, FolderSummary, FolderCompletion, } }
Change the pattern for matches-time
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Calculation.Predicate.Text { class TextMatchesTime : CultureSensitiveTextPredicate { public TextMatchesTime(bool not, string culture) : base(not, culture) { } protected override bool Apply(object x) { switch (x) { case string s: return System.DateTime.TryParseExact(s, CultureInfo.DateTimeFormat.ShortTimePattern, CultureInfo, DateTimeStyles.None, out var result); default: return System.DateTime.TryParse(x.ToString(), out var result2); } } public override string ToString() { return $"matches the short time pattern format '{CultureInfo.DateTimeFormat.ShortTimePattern.Replace("/", CultureInfo.DateTimeFormat.TimeSeparator)}'"; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Calculation.Predicate.Text { class TextMatchesTime : CultureSensitiveTextPredicate { public TextMatchesTime(bool not, string culture) : base(not, culture) { } protected override bool Apply(object x) { switch (x) { case string s: return System.DateTime.TryParseExact(s, CultureInfo.DateTimeFormat.LongTimePattern, CultureInfo, DateTimeStyles.None, out var result); default: return System.DateTime.TryParse(x.ToString(), out var result2); } } public override string ToString() { return $"matches the short time pattern format '{CultureInfo.DateTimeFormat.ShortTimePattern.Replace("/", CultureInfo.DateTimeFormat.TimeSeparator)}'"; } } }
Add title to android notifications object
namespace CertiPay.Common.Notifications.Notifications { public class AndroidNotification : Notification { public static string QueueName { get { return "AndroidNotifications"; } } // TODO Android specific properties? Title, Image, Sound, Action Button, Picture, Priority // Message => Content } }
using System; namespace CertiPay.Common.Notifications.Notifications { public class AndroidNotification : Notification { public static string QueueName { get; } = "AndroidNotifications"; // Message => Content /// <summary> /// The subject line of the email /// </summary> public String Title { get; set; } // TODO Android specific properties? Image, Sound, Action Button, Picture, Priority } }
Add static constructor for scripting environment
namespace GraduatedCylinder.Geo { public class GeoPosition { private readonly Length _altitude; private readonly Latitude _latitude; private readonly Longitude _longitude; public GeoPosition(Latitude latitude, Longitude longitude, Length altitude = null) { _latitude = latitude; _longitude = longitude; _altitude = altitude; } public Length Altitude { get { return _altitude; } } public Latitude Latitude { get { return _latitude; } } public Longitude Longitude { get { return _longitude; } } public override string ToString() { return "{" + Latitude + ", " + Longitude + "}"; } } }
namespace GraduatedCylinder.Geo { public class GeoPosition { private readonly Length _altitude; private readonly Latitude _latitude; private readonly Longitude _longitude; public GeoPosition(Latitude latitude, Longitude longitude, Length altitude = null) { _latitude = latitude; _longitude = longitude; _altitude = altitude; } public Length Altitude { get { return _altitude; } } public Latitude Latitude { get { return _latitude; } } public Longitude Longitude { get { return _longitude; } } public override string ToString() { return "{" + Latitude + ", " + Longitude + "}"; } public static GeoPosition New(Latitude latitude, Longitude longitude, Length altitude = null) { return new GeoPosition(latitude, longitude, altitude); } } }
Remove using statement referring to Awesomium.
using Awesomium.Core; using MVVM.CEFGlue.Infra; using MVVM.CEFGlue.ViewModel.Example; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace MVVM.CEFGlue.UI.SelectedItems { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var datacontext = new SkillsViewModel(); datacontext.Skills.Add(new Skill() {Name="knockout", Type="Info" }); datacontext.SelectedSkills.Add(datacontext.Skills[0]); DataContext = datacontext; } protected override void OnClosed(EventArgs e) { base.OnClosed(e); this.WebControl.Dispose(); } } }
using MVVM.CEFGlue.Infra; using MVVM.CEFGlue.ViewModel.Example; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace MVVM.CEFGlue.UI.SelectedItems { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var datacontext = new SkillsViewModel(); datacontext.Skills.Add(new Skill() {Name="knockout", Type="Info" }); datacontext.SelectedSkills.Add(datacontext.Skills[0]); DataContext = datacontext; } protected override void OnClosed(EventArgs e) { base.OnClosed(e); this.WebControl.Dispose(); } } }
Fix launching help through API on Linux (BL-4577)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using Bloom.Api; using SIL.IO; namespace Bloom { public class HelpLauncher { public static void Show(Control parent) { Help.ShowHelp(parent, FileLocator.GetFileDistributedWithApplication("Bloom.chm")); } public static void Show(Control parent, string topic) { Show(parent, "Bloom.chm", topic); } public static void Show(Control parent, string helpFileName, string topic) { Help.ShowHelp(parent, FileLocator.GetFileDistributedWithApplication(helpFileName), topic); } public static void RegisterWithServer(EnhancedImageServer server) { server.RegisterEndpointHandler("help/.*", (request) => { var topic = request.LocalPath().ToLowerInvariant().Replace("api/help",""); Show(Application.OpenForms.Cast<Form>().Last(), topic); //if this is called from a simple html anchor, we don't want the browser to do anything request.ExternalLinkSucceeded(); }, true); // opening a form, definitely UI thread } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using Bloom.Api; using SIL.IO; namespace Bloom { public class HelpLauncher { public static void Show(Control parent) { Help.ShowHelp(parent, FileLocator.GetFileDistributedWithApplication("Bloom.chm")); } public static void Show(Control parent, string topic) { Show(parent, "Bloom.chm", topic); } public static void Show(Control parent, string helpFileName, string topic) { Help.ShowHelp(parent, FileLocator.GetFileDistributedWithApplication(helpFileName), topic); } public static void RegisterWithServer(EnhancedImageServer server) { server.RegisterEndpointHandler("help/.*", (request) => { var topic = request.LocalPath().Replace("api/help",""); Show(Application.OpenForms.Cast<Form>().Last(), topic); //if this is called from a simple html anchor, we don't want the browser to do anything request.ExternalLinkSucceeded(); }, true); // opening a form, definitely UI thread } } }
Fix for Nancy view conventions and static content conventions
using System; using Nancy; using Nancy.Conventions; using System.IO; namespace OpenIDConnect.Clients.Angular14.Bootstrap { public class CustomNancyBootstrapper : DefaultNancyBootstrapper { protected override IRootPathProvider RootPathProvider { get { return new CustomRootPathProvider(new DefaultRootPathProvider()); } } } internal class CustomRootPathProvider : IRootPathProvider { private readonly IRootPathProvider provider; public CustomRootPathProvider(IRootPathProvider provider) { this.provider = provider; } public string GetRootPath() { var path = Path.Combine(this.provider.GetRootPath(), "content/dist/"); return path; } } }
using Nancy; using Nancy.Conventions; using Nancy.TinyIoc; namespace OpenIDConnect.Clients.Angular14.Bootstrap { public class CustomNancyBootstrapper : DefaultNancyBootstrapper { protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { this.Conventions.ViewLocationConventions.Add((viewName, model, context) => { return string.Concat("content/dist/", viewName); }); } protected override void ConfigureConventions(NancyConventions conventions) { base.ConfigureConventions(conventions); conventions.StaticContentsConventions.AddDirectory("", "content/dist"); } } }
Fix "most played beatmap" request breakage after property rename
// 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 Newtonsoft.Json; using osu.Game.Beatmaps; using osu.Game.Rulesets; namespace osu.Game.Online.API.Requests.Responses { public class APIUserMostPlayedBeatmap { [JsonProperty("beatmap_id")] public int BeatmapID { get; set; } [JsonProperty("count")] public int PlayCount { get; set; } [JsonProperty] private BeatmapInfo beatmapInfo { get; set; } [JsonProperty] private APIBeatmapSet beatmapSet { get; set; } public BeatmapInfo GetBeatmapInfo(RulesetStore rulesets) { BeatmapSetInfo setInfo = beatmapSet.ToBeatmapSet(rulesets); beatmapInfo.BeatmapSet = setInfo; beatmapInfo.Metadata = setInfo.Metadata; return beatmapInfo; } } }
// 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 Newtonsoft.Json; using osu.Game.Beatmaps; using osu.Game.Rulesets; namespace osu.Game.Online.API.Requests.Responses { public class APIUserMostPlayedBeatmap { [JsonProperty("beatmap_id")] public int BeatmapID { get; set; } [JsonProperty("count")] public int PlayCount { get; set; } [JsonProperty("beatmap")] private BeatmapInfo beatmapInfo { get; set; } [JsonProperty] private APIBeatmapSet beatmapSet { get; set; } public BeatmapInfo GetBeatmapInfo(RulesetStore rulesets) { BeatmapSetInfo setInfo = beatmapSet.ToBeatmapSet(rulesets); beatmapInfo.BeatmapSet = setInfo; beatmapInfo.Metadata = setInfo.Metadata; return beatmapInfo; } } }
Fix a bug where decompiled code input was not working
using ImGuiNET; using OpenKh.Tools.Kh2MapStudio.Models; using System.Numerics; using static OpenKh.Tools.Common.CustomImGui.ImGuiEx; namespace OpenKh.Tools.Kh2MapStudio.Windows { static class SpawnScriptWindow { private static readonly Vector4 ErrorColor = new Vector4(1.0f, 0.0f, 0.0f, 1.0f); private static readonly Vector4 SuccessColor = new Vector4(0.0f, 1.0f, 0.0f, 1.0f); public static bool Run(string type, SpawnScriptModel model) => ForWindow($"Spawn Script compiler for {type}", () => { if (model == null) { ImGui.TextWrapped($"Unable to find for '{type}'."); return; } if (ImGui.Button($"Compile##{type}")) model.Compile(); if (!string.IsNullOrEmpty(model.LastError)) ImGui.TextColored(model.IsError ? ErrorColor : SuccessColor, model.LastError); var code = model.Decompiled; if (ImGui.InputTextMultiline($"code##{type}", ref code, int.MaxValue, new Vector2(0, 0))) model.Decompiled = code; }); } }
using ImGuiNET; using OpenKh.Tools.Kh2MapStudio.Models; using System.Numerics; using static OpenKh.Tools.Common.CustomImGui.ImGuiEx; namespace OpenKh.Tools.Kh2MapStudio.Windows { static class SpawnScriptWindow { private static readonly Vector4 ErrorColor = new Vector4(1.0f, 0.0f, 0.0f, 1.0f); private static readonly Vector4 SuccessColor = new Vector4(0.0f, 1.0f, 0.0f, 1.0f); public static bool Run(string type, SpawnScriptModel model) => ForWindow($"Spawn Script compiler for {type}", () => { if (model == null) { ImGui.TextWrapped($"Unable to find for '{type}'."); return; } if (ImGui.Button($"Compile##{type}")) model.Compile(); if (!string.IsNullOrEmpty(model.LastError)) ImGui.TextColored(model.IsError ? ErrorColor : SuccessColor, model.LastError); var code = model.Decompiled; if (ImGui.InputTextMultiline($"code##{type}", ref code, 0x100000, new Vector2(0, 0))) model.Decompiled = code; }); } }
Use a different database name for now to avoid conflicts when switching versions
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Platform; namespace osu.Game.Database { public class DatabaseContextFactory { private readonly GameHost host; public DatabaseContextFactory(GameHost host) { this.host = host; } public OsuDbContext GetContext() => new OsuDbContext(host.Storage.GetDatabaseConnectionString(@"client")); } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Platform; namespace osu.Game.Database { public class DatabaseContextFactory { private readonly GameHost host; public DatabaseContextFactory(GameHost host) { this.host = host; } public OsuDbContext GetContext() => new OsuDbContext(host.Storage.GetDatabaseConnectionString(@"client-ef")); } }
Set focus on search box when select page visible
using System.ComponentModel.Composition; using System.Windows.Controls; using System.Windows.Input; using GitHub.Exports; using GitHub.ViewModels.Dialog.Clone; namespace GitHub.VisualStudio.Views.Dialog.Clone { [ExportViewFor(typeof(IRepositorySelectViewModel))] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class SelectPageView : UserControl { public SelectPageView() { InitializeComponent(); } protected override void OnPreviewMouseDown(MouseButtonEventArgs e) { base.OnPreviewMouseDown(e); } } }
using System; using System.ComponentModel.Composition; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Threading; using GitHub.Exports; using GitHub.ViewModels.Dialog.Clone; namespace GitHub.VisualStudio.Views.Dialog.Clone { [ExportViewFor(typeof(IRepositorySelectViewModel))] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class SelectPageView : UserControl { public SelectPageView() { InitializeComponent(); // See Douglas Stockwell's suggestion here: // https://social.msdn.microsoft.com/Forums/vstudio/en-US/30ed27ce-f7b7-48ae-8adc-0400b9b9ec78 IsVisibleChanged += (sender, e) => { if (IsVisible) { Dispatcher.BeginInvoke(DispatcherPriority.Input, (Action)(() => SearchTextBox.Focus())); } }; } protected override void OnPreviewMouseDown(MouseButtonEventArgs e) { base.OnPreviewMouseDown(e); } } }
Set env vars in GitHub Actions
namespace NerdBank.GitVersioning.CloudBuildServices { using System; using System.Collections.Generic; using System.IO; using Nerdbank.GitVersioning; internal class GitHubActions : ICloudBuild { public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent"; public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null; public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null; public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA"); private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF"); public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } } }
namespace NerdBank.GitVersioning.CloudBuildServices { using System; using System.Collections.Generic; using System.IO; using Nerdbank.GitVersioning; internal class GitHubActions : ICloudBuild { public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent"; public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null; public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null; public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA"); private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF"); public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##[set-env name={name};]{value}"); return GetDictionaryFor(name, value); } private static IReadOnlyDictionary<string, string> GetDictionaryFor(string variableName, string value) { return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { GetEnvironmentVariableNameForVariable(variableName), value }, }; } private static string GetEnvironmentVariableNameForVariable(string name) => name.ToUpperInvariant().Replace('.', '_'); } }
Adjust diffcalc test case to pass
// 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(); } }
// 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.2867022617692685d, "diffcalc-test")] [TestCase(2.2867022617692685d, "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(); } }
Reset version number (will be updated by gitversion)
using System.Reflection; using System.Runtime.InteropServices; #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyProduct("UsageStats")] [assembly: AssemblyCompany("UsageStats")] [assembly: AssemblyCopyright("© UsageStats contributors. All rights reserved.")] [assembly: AssemblyTrademark("")] // [assembly: CLSCompliant(true)] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version numbers will be updated by the build script [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyFileVersion("2.0.0")]
using System.Reflection; using System.Runtime.InteropServices; #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyProduct("UsageStats")] [assembly: AssemblyCompany("UsageStats")] [assembly: AssemblyCopyright("© UsageStats contributors. All rights reserved.")] [assembly: AssemblyTrademark("")] // [assembly: CLSCompliant(true)] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version numbers will be updated by the build script [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyFileVersion("0.1.0")]
Increment minor build number for release
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyTitle("PowerBridge")] [assembly: AssemblyDescription("Build tasks that enable running PowerShell scripts from MSBuild.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rafael Dowling Goodman")] [assembly: AssemblyProduct("PowerBridge")] [assembly: AssemblyCopyright("Copyright © Rafael Dowling Goodman 2014")] [assembly: AssemblyVersion("1.1.*")] [assembly: NeutralResourcesLanguageAttribute("en-US")] [assembly: InternalsVisibleTo("PowerBridge.Tests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyTitle("PowerBridge")] [assembly: AssemblyDescription("Build tasks that enable running PowerShell scripts from MSBuild.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rafael Dowling Goodman")] [assembly: AssemblyProduct("PowerBridge")] [assembly: AssemblyCopyright("Copyright © Rafael Dowling Goodman 2014")] [assembly: AssemblyVersion("1.2.*")] [assembly: NeutralResourcesLanguageAttribute("en-US")] [assembly: InternalsVisibleTo("PowerBridge.Tests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
Improve error, when test name is invalid
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.NodejsTools.TestAdapter.TestFrameworks { internal class NodejsTestInfo { public NodejsTestInfo(string fullyQualifiedName) { var parts = fullyQualifiedName.Split(new[] { "::" }, StringSplitOptions.None); if (parts.Length != 3) { throw new ArgumentException("Invalid fully qualified test name", nameof(fullyQualifiedName)); } this.ModulePath = parts[0]; this.TestName = parts[1]; this.TestFramework = parts[2]; } public NodejsTestInfo(string modulePath, string testName, string testFramework, int line, int column) { this.ModulePath = modulePath; this.TestName = testName; this.TestFramework = testFramework; this.SourceLine = line; this.SourceColumn = column; } public string FullyQualifiedName => $"{this.ModulePath}::{this.TestName}::{this.TestFramework}"; public string ModulePath { get; } public string TestName { get; } public string TestFramework { get; } public int SourceLine { get; } public int SourceColumn { get; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.NodejsTools.TestAdapter.TestFrameworks { internal class NodejsTestInfo { public NodejsTestInfo(string fullyQualifiedName) { var parts = fullyQualifiedName.Split(new[] { "::" }, StringSplitOptions.None); if (parts.Length != 3) { throw new ArgumentException($"Invalid fully qualified test name. '{fullyQualifiedName}'", nameof(fullyQualifiedName)); } this.ModulePath = parts[0]; this.TestName = parts[1]; this.TestFramework = parts[2]; } public NodejsTestInfo(string modulePath, string testName, string testFramework, int line, int column) { this.ModulePath = modulePath; this.TestName = testName; this.TestFramework = testFramework; this.SourceLine = line; this.SourceColumn = column; } public string FullyQualifiedName => $"{this.ModulePath}::{this.TestName}::{this.TestFramework}"; public string ModulePath { get; } public string TestName { get; } public string TestFramework { get; } public int SourceLine { get; } public int SourceColumn { get; } } }
Format speaker bio on index page as well.
using FacetedWorlds.MyCon.Model; using System.Linq; using System.Collections.Generic; namespace FacetedWorlds.MyCon.Web.ViewModels { public class SpeakerViewModel { private readonly Speaker _speaker; public SpeakerViewModel(Speaker speaker) { _speaker = speaker; } public string Name { get { return _speaker.Name; } } public string ImageUrl { get { return _speaker.ImageUrl; } } public string Bio { get { IEnumerable<DocumentSegment> segments = _speaker.Bio.Value; if (segments == null) return string.Empty; return string.Join("", segments.Select(segment => segment.Text).ToArray()); } } } }
using FacetedWorlds.MyCon.Model; using System.Linq; using System.Collections.Generic; using System.Web.Mvc; using FacetedWorlds.MyCon.Web.Extensions; namespace FacetedWorlds.MyCon.Web.ViewModels { public class SpeakerViewModel { private readonly Speaker _speaker; public SpeakerViewModel(Speaker speaker) { _speaker = speaker; } public string Name { get { return _speaker.Name; } } public string ImageUrl { get { return _speaker.ImageUrl; } } public MvcHtmlString Bio { get { IEnumerable<DocumentSegment> segments = _speaker.Bio.Value; return segments.AsHtml(); } } } }
Tweak how the entries are listed, only showing since the last balance key
using Cash_Flow_Projection.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Threading.Tasks; namespace Cash_Flow_Projection.Controllers { public class HomeController : Controller { private readonly Database db; public HomeController(Database db) { this.db = db; } public async Task<IActionResult> Index() { return View(new Dashboard { Entries = db.Entries }); } public async Task<IActionResult> ByMonth(int month, int year) { // Cash at beginning of month // Projections for each day of the month? // Income vs Expenses // Ending balance (excess/deficit of cash) return View(); } public IActionResult Add() { return View(new Entry { }); } [HttpPost] public async Task<IActionResult> Add(Entry entry) { db.Entries.Add(entry); db.SaveChanges(); return RedirectToAction(nameof(Index)); } [HttpDelete] public async Task<IActionResult> Delete(String id) { var entry = db.Entries.Single(_ => _.id == id); db.Entries.Remove(entry); db.SaveChanges(); return Json(new { success = true }); } public IActionResult Error() { return View(); } } }
using Cash_Flow_Projection.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Threading.Tasks; namespace Cash_Flow_Projection.Controllers { public class HomeController : Controller { private readonly Database db; public HomeController(Database db) { this.db = db; } public async Task<IActionResult> Index() { var last_balance = db.Entries.GetLastBalanceEntry(); var entries = from entry in db.Entries where entry.Date >= last_balance.Date orderby entry.Date descending select entry; return View(new Dashboard { Entries = entries }); } public async Task<IActionResult> ByMonth(int month, int year) { // Cash at beginning of month // Projections for each day of the month? // Income vs Expenses // Ending balance (excess/deficit of cash) return View(); } public IActionResult Add() { return View(new Entry { }); } [HttpPost] public async Task<IActionResult> Add(Entry entry) { db.Entries.Add(entry); db.SaveChanges(); return RedirectToAction(nameof(Index)); } [HttpDelete] public async Task<IActionResult> Delete(String id) { var entry = db.Entries.Single(_ => _.id == id); db.Entries.Remove(entry); db.SaveChanges(); return Json(new { success = true }); } public IActionResult Error() { return View(); } } }
Increase number of grid objects.
using ProjectCDA.Model; using System.Collections.ObjectModel; using System.ComponentModel; namespace ProjectCDA.Data { public class DataSource : INotifyPropertyChanged { private ObservableCollection<TwoPages> _Schedule; public DataSource() { AddSomeDummyData(); } public ObservableCollection<TwoPages> Schedule { get { return _Schedule; } set { if (value != _Schedule) { _Schedule = value; PropertyChanged(this, new PropertyChangedEventArgs("Schedule")); } } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void AddSomeDummyData() { ObservableCollection<TwoPages> TmpSchedule = new ObservableCollection<TwoPages>(); TwoPages pages = new TwoPages(); pages.ID = 0; pages.hasNumbers = true; pages.hasHeaderField = true; TmpSchedule.Add(pages); pages = new TwoPages(); pages.ID = 1; pages.hasNumbers = true; pages.hasHeaderField = false; TmpSchedule.Add(pages); pages = new TwoPages(); pages.ID = 2; pages.hasNumbers = false; pages.hasHeaderField = false; TmpSchedule.Add(pages); for (int i=3; i<30; i++) { pages = new TwoPages(); pages.ID = i; pages.hasNumbers = true; pages.hasHeaderField = true; TmpSchedule.Add(pages); } Schedule = TmpSchedule; } } }
using ProjectCDA.Model; using System.Collections.ObjectModel; using System.ComponentModel; namespace ProjectCDA.Data { public class DataSource : INotifyPropertyChanged { private ObservableCollection<TwoPages> _Schedule; public DataSource() { AddSomeDummyData(); } public ObservableCollection<TwoPages> Schedule { get { return _Schedule; } set { if (value != _Schedule) { _Schedule = value; PropertyChanged(this, new PropertyChangedEventArgs("Schedule")); } } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void AddSomeDummyData() { ObservableCollection<TwoPages> TmpSchedule = new ObservableCollection<TwoPages>(); TwoPages pages = new TwoPages(); pages.ID = 0; pages.hasNumbers = true; pages.hasHeaderField = true; TmpSchedule.Add(pages); pages = new TwoPages(); pages.ID = 1; pages.hasNumbers = true; pages.hasHeaderField = false; TmpSchedule.Add(pages); pages = new TwoPages(); pages.ID = 2; pages.hasNumbers = false; pages.hasHeaderField = false; TmpSchedule.Add(pages); for (int i=3; i<65; i++) { pages = new TwoPages(); pages.ID = i; pages.hasNumbers = true; pages.hasHeaderField = true; TmpSchedule.Add(pages); } Schedule = TmpSchedule; } } }
Fix the asset that you try and get
using System.Threading.Tasks; using Glimpse.Internal; using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; namespace Glimpse.AgentServer.AspNet.Sample { public class SamplePage { private readonly ContextData<MessageContext> _context; public SamplePage() { _context = new ContextData<MessageContext>(); } public async Task Invoke(HttpContext context) { var response = context.Response; response.Headers[HeaderNames.ContentType] = "text/html"; await response.WriteAsync($"<html><body><h1>Agent Test</h1><script src='/Glimpse/Browser/Agent' id='glimpse' data-glimpse-id='{_context?.Value?.Id}'></script></body></html>"); } } }
using System.Threading.Tasks; using Glimpse.Internal; using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; namespace Glimpse.AgentServer.AspNet.Sample { public class SamplePage { private readonly ContextData<MessageContext> _context; public SamplePage() { _context = new ContextData<MessageContext>(); } public async Task Invoke(HttpContext context) { var response = context.Response; response.Headers[HeaderNames.ContentType] = "text/html"; await response.WriteAsync($"<html><body><h1>Agent Test</h1><script src='/glimpse/agent/agent.js?hash=213' id='glimpse' data-glimpse-id='{_context?.Value?.Id}'></script></body></html>"); } } }
Fix 0 size in test scene
// 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.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Multiplayer; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Multi.Components; using osu.Game.Tests.Beatmaps; using osuTK; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneOverlinedPlaylist : MultiplayerTestScene { protected override bool UseOnlineAPI => true; public TestSceneOverlinedPlaylist() { for (int i = 0; i < 10; i++) { Room.Playlist.Add(new PlaylistItem { ID = i, Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo }, Ruleset = { Value = new OsuRuleset().RulesetInfo } }); } Add(new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500), Child = new OverlinedPlaylist(false) }); } } }
// 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.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Multiplayer; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Multi.Components; using osu.Game.Tests.Beatmaps; using osuTK; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneOverlinedPlaylist : MultiplayerTestScene { protected override bool UseOnlineAPI => true; public TestSceneOverlinedPlaylist() { for (int i = 0; i < 10; i++) { Room.Playlist.Add(new PlaylistItem { ID = i, Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo }, Ruleset = { Value = new OsuRuleset().RulesetInfo } }); } Add(new OverlinedPlaylist(false) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500), }); } } }
Update http request count default name.
namespace Prometheus.HttpExporter.AspNetCore.HttpRequestCount { public class HttpRequestCountOptions : HttpExporterOptionsBase { public Counter Counter { get; set; } = Metrics.CreateCounter(DefaultName, DefaultHelp, HttpRequestLabelNames.All); private const string DefaultName = "aspnet_http_request_count"; private const string DefaultHelp = "Provides the count of HTTP requests from an ASP.NET application."; } }
namespace Prometheus.HttpExporter.AspNetCore.HttpRequestCount { public class HttpRequestCountOptions : HttpExporterOptionsBase { public Counter Counter { get; set; } = Metrics.CreateCounter(DefaultName, DefaultHelp, HttpRequestLabelNames.All); private const string DefaultName = "aspnet_http_requests_total"; private const string DefaultHelp = "Provides the count of HTTP requests from an ASP.NET application."; } }
Add Exclusion Service to SerializeStep
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Fasterflect; namespace Testity.BuildProcess.Unity3D { public class AddSerializedMemberStep : ITestityBuildStep { private readonly ITypeRelationalMapper typeResolver; private readonly ITypeMemberParser typeParser; public AddSerializedMemberStep(ITypeRelationalMapper mapper, ITypeMemberParser parser) { typeResolver = mapper; typeParser = parser; } public void Process(IClassBuilder builder, Type typeToParse) { //This can be done in a way that preserves order but that is not important in the first Testity build. //We can improve on that later //handle serialized fields and properties foreach (MemberInfo mi in typeParser.Parse(MemberTypes.Field | MemberTypes.Property, typeToParse)) { builder.AddClassField(new UnitySerializedFieldImplementationProvider(mi.Name, typeResolver.ResolveMappedType(mi.Type()), new Common.Unity3D.WiredToAttribute(mi.MemberType, mi.Name, mi.Type()))); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Fasterflect; namespace Testity.BuildProcess.Unity3D { public class AddSerializedMemberStep : ITestityBuildStep { private readonly ITypeRelationalMapper typeResolver; private readonly ITypeMemberParser typeParser; private readonly ITypeExclusion typesNotToSerialize; public AddSerializedMemberStep(ITypeRelationalMapper mapper, ITypeMemberParser parser, ITypeExclusion typeExclusionService) { typeResolver = mapper; typeParser = parser; typesNotToSerialize = typeExclusionService; } public void Process(IClassBuilder builder, Type typeToParse) { //This can be done in a way that preserves order but that is not important in the first Testity build. //We can improve on that later //handle serialized fields and properties foreach (MemberInfo mi in typeParser.Parse(MemberTypes.Field | MemberTypes.Property, typeToParse)) { //Some types are no serialized or are serialized in later steps if (typesNotToSerialize.isExcluded(mi.Type())) continue; builder.AddClassField(new UnitySerializedFieldImplementationProvider(mi.Name, typeResolver.ResolveMappedType(mi.Type()), new Common.Unity3D.WiredToAttribute(mi.MemberType, mi.Name, mi.Type()))); } } } }
Add required config property to json client adapter
using IntegrationEngine.Core.Configuration; using ServiceStack.ServiceClient.Web; using System.Net; namespace IntegrationEngine.Core.ServiceStack { public class JsonServiceClientAdapter : JsonServiceClient, IJsonServiceClient { public JsonServiceClientAdapter(IJsonServiceConfiguration jsonServiceConfiguration) : base(jsonServiceConfiguration.BaseUri) { UserName = jsonServiceConfiguration.UserName; Password = jsonServiceConfiguration.Password; AlwaysSendBasicAuthHeader = jsonServiceConfiguration.AlwaysSendBasicAuthHeader; } } }
using IntegrationEngine.Core.Configuration; using ServiceStack.ServiceClient.Web; using System.Net; namespace IntegrationEngine.Core.ServiceStack { public class JsonServiceClientAdapter : JsonServiceClient, IJsonServiceClient { public IJsonServiceConfiguration JsonServiceConfiguration { get; set; } public JsonServiceClientAdapter() { } public JsonServiceClientAdapter(IJsonServiceConfiguration jsonServiceConfiguration) : base(jsonServiceConfiguration.BaseUri) { UserName = jsonServiceConfiguration.UserName; Password = jsonServiceConfiguration.Password; AlwaysSendBasicAuthHeader = jsonServiceConfiguration.AlwaysSendBasicAuthHeader; JsonServiceConfiguration = jsonServiceConfiguration; } } }
Include source in symbols package.
using Cake.Common.Tools.DotNetCore; using Cake.Common.Tools.DotNetCore.Pack; using Cake.Core; using Cake.Core.IO; using Cake.Frosting; [Dependency(typeof(UnitTests))] public class Package : FrostingTask<Context> { public override void Run(Context context) { var path = new FilePath("./src/Cake.Frosting/Cake.Frosting.csproj"); context.DotNetCorePack(path.FullPath, new DotNetCorePackSettings(){ Configuration = context.Configuration, VersionSuffix = context.Version.Suffix, NoBuild = true, Verbose = false, ArgumentCustomization = args => args.Append("--include-symbols") }); } }
using Cake.Common.Tools.DotNetCore; using Cake.Common.Tools.DotNetCore.Pack; using Cake.Core; using Cake.Core.IO; using Cake.Frosting; [Dependency(typeof(UnitTests))] public class Package : FrostingTask<Context> { public override void Run(Context context) { var path = new FilePath("./src/Cake.Frosting/Cake.Frosting.csproj"); context.DotNetCorePack(path.FullPath, new DotNetCorePackSettings(){ Configuration = context.Configuration, VersionSuffix = context.Version.Suffix, NoBuild = true, Verbose = false, ArgumentCustomization = args => args.Append("--include-symbols --include-source") }); } }
Disable argument checks for now
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ExtensionsDataModule.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel { using Catel.IoC; /// <summary> /// Extensions.Data module which allows the registration of default services in the service locator. /// </summary> public class ExtensionsDataModule : IServiceLocatorInitializer { /// <summary> /// Initializes the specified service locator. /// </summary> /// <param name="serviceLocator">The service locator.</param> public void Initialize(IServiceLocator serviceLocator) { Argument.IsNotNull(() => serviceLocator); // Register services here } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ExtensionsDataModule.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel { using Catel.IoC; /// <summary> /// Extensions.Data module which allows the registration of default services in the service locator. /// </summary> public class ExtensionsDataModule : IServiceLocatorInitializer { /// <summary> /// Initializes the specified service locator. /// </summary> /// <param name="serviceLocator">The service locator.</param> public void Initialize(IServiceLocator serviceLocator) { //Argument.IsNotNull(() => serviceLocator); // Register services here } } }
Use TypeNameHandling.Objects when serializing objects to json.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; namespace SlashTodo.Infrastructure.AzureTables { public abstract class ComplexTableEntity<T> : TableEntity { private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; public string SerializedData { get; set; } protected ComplexTableEntity() { } protected ComplexTableEntity(T data, Func<T, string> partitionKey, Func<T, string> rowKey) { PartitionKey = partitionKey(data); RowKey = rowKey(data); SerializedData = JsonConvert.SerializeObject(data, SerializerSettings); } public T GetData() { return (T)JsonConvert.DeserializeObject(SerializedData, SerializerSettings); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; namespace SlashTodo.Infrastructure.AzureTables { public abstract class ComplexTableEntity<T> : TableEntity { private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects }; public string SerializedData { get; set; } protected ComplexTableEntity() { } protected ComplexTableEntity(T data, Func<T, string> partitionKey, Func<T, string> rowKey) { PartitionKey = partitionKey(data); RowKey = rowKey(data); SerializedData = JsonConvert.SerializeObject(data, SerializerSettings); } public T GetData() { return (T)JsonConvert.DeserializeObject(SerializedData, SerializerSettings); } } }
Fix extensions when using dotnet adapter
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if (UNITY_WSA && DOTNETWINRT_PRESENT) || WINDOWS_UWP using Microsoft.MixedReality.Toolkit.Utilities; using Windows.UI.Input.Spatial; #endif // (UNITY_WSA && DOTNETWINRT_PRESENT) || WINDOWS_UWP namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality { /// <summary> /// Provides useful extensions for Windows-defined types. /// </summary> public static class WindowsExtensions { #if (UNITY_WSA && DOTNETWINRT_PRESENT) || WINDOWS_UWP /// <summary> /// Converts a platform <see cref="SpatialInteractionSourceHandedness"/> into /// the equivalent value in MRTK's defined <see cref="Handedness"/>. /// </summary> /// <param name="handedness">The handedness value to convert.</param> /// <returns>The converted value in the new type.</returns> public static Handedness ToMRTKHandedness(this SpatialInteractionSourceHandedness handedness) { switch (handedness) { case SpatialInteractionSourceHandedness.Left: return Handedness.Left; case SpatialInteractionSourceHandedness.Right: return Handedness.Right; case SpatialInteractionSourceHandedness.Unspecified: default: return Handedness.None; } } #endif // (UNITY_WSA && DOTNETWINRT_PRESENT) || WINDOWS_UWP } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if (UNITY_WSA && DOTNETWINRT_PRESENT) || WINDOWS_UWP using Microsoft.MixedReality.Toolkit.Utilities; #if WINDOWS_UWP using Windows.UI.Input.Spatial; #elif DOTNETWINRT_PRESENT using Microsoft.Windows.UI.Input.Spatial; #endif #endif // (UNITY_WSA && DOTNETWINRT_PRESENT) || WINDOWS_UWP namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality { /// <summary> /// Provides useful extensions for Windows-defined types. /// </summary> public static class WindowsExtensions { #if (UNITY_WSA && DOTNETWINRT_PRESENT) || WINDOWS_UWP /// <summary> /// Converts a platform <see cref="SpatialInteractionSourceHandedness"/> into /// the equivalent value in MRTK's defined <see cref="Handedness"/>. /// </summary> /// <param name="handedness">The handedness value to convert.</param> /// <returns>The converted value in the new type.</returns> public static Handedness ToMRTKHandedness(this SpatialInteractionSourceHandedness handedness) { switch (handedness) { case SpatialInteractionSourceHandedness.Left: return Handedness.Left; case SpatialInteractionSourceHandedness.Right: return Handedness.Right; case SpatialInteractionSourceHandedness.Unspecified: default: return Handedness.None; } } #endif // (UNITY_WSA && DOTNETWINRT_PRESENT) || WINDOWS_UWP } }
Handle SelectPrevious / SelectNext as volume change operations if nothing else handled game-wide
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.Containers; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Game.Input.Bindings; namespace osu.Game.Overlays.Volume { public class VolumeControlReceptor : Container, IScrollBindingHandler<GlobalAction>, IHandleGlobalKeyboardInput { public Func<GlobalAction, bool> ActionRequested; public Func<GlobalAction, float, bool, bool> ScrollActionRequested; public bool OnPressed(GlobalAction action) => ActionRequested?.Invoke(action) ?? false; public bool OnScroll(GlobalAction action, float amount, bool isPrecise) => ScrollActionRequested?.Invoke(action, amount, isPrecise) ?? false; public void OnReleased(GlobalAction action) { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.Containers; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Game.Input.Bindings; namespace osu.Game.Overlays.Volume { public class VolumeControlReceptor : Container, IScrollBindingHandler<GlobalAction>, IHandleGlobalKeyboardInput { public Func<GlobalAction, bool> ActionRequested; public Func<GlobalAction, float, bool, bool> ScrollActionRequested; public bool OnPressed(GlobalAction action) { // if nothing else handles selection actions in the game, it's safe to let volume be adjusted. switch (action) { case GlobalAction.SelectPrevious: action = GlobalAction.IncreaseVolume; break; case GlobalAction.SelectNext: action = GlobalAction.DecreaseVolume; break; } return ActionRequested?.Invoke(action) ?? false; } public bool OnScroll(GlobalAction action, float amount, bool isPrecise) => ScrollActionRequested?.Invoke(action, amount, isPrecise) ?? false; public void OnReleased(GlobalAction action) { } } }
Add test for filtered mode
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Tests.Visual.Settings { public class TestSceneFileSelector : OsuTestScene { [BackgroundDependencyLoader] private void load() { Add(new FileSelector { RelativeSizeAxes = Axes.Both }); } } }
// 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.Framework.Graphics; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Tests.Visual.Settings { public class TestSceneFileSelector : OsuTestScene { [Test] public void TestAllFiles() { AddStep("create", () => Child = new FileSelector { RelativeSizeAxes = Axes.Both }); } [Test] public void TestJpgFilesOnly() { AddStep("create", () => Child = new FileSelector(validFileExtensions: new[] { ".jpg" }) { RelativeSizeAxes = Axes.Both }); } } }
Use UrlEncode from OAuth lib
using System; using System.Collections.Generic; using System.Text; namespace SevenDigital.Api.Wrapper.EndpointResolution { public static class DictionaryExtensions { public static string ToQueryString(this IDictionary<string, string> collection) { var sb = new StringBuilder(); foreach (var key in collection.Keys) { var parameter = Uri.EscapeDataString(collection[key]); sb.AppendFormat("{0}={1}&", key, parameter); } return sb.ToString().TrimEnd('&'); } } }
using System.Collections.Generic; using System.Text; using OAuth; namespace SevenDigital.Api.Wrapper.EndpointResolution { public static class DictionaryExtensions { public static string ToQueryString(this IDictionary<string, string> collection) { var sb = new StringBuilder(); foreach (var key in collection.Keys) { var parameter = OAuthTools.UrlEncodeRelaxed(collection[key]); sb.AppendFormat("{0}={1}&", key, parameter); } return sb.ToString().TrimEnd('&'); } } }
Add flying players setting to extension loader
using System; using BotBits; namespace BotBitsExt.Rounds { public sealed class RoundsExtension : Extension<RoundsExtension> { private class Settings { public int MinimumPlayers { get; private set; } public int WaitTime { get; private set; } public bool FlyingPlayersCanPlay { get; private set; } public Settings(int minimumPlayers, int waitTime, bool flyingPlayersCanPlay = false) { MinimumPlayers = minimumPlayers; WaitTime = waitTime; FlyingPlayersCanPlay = flyingPlayersCanPlay; } } protected override void Initialize(BotBitsClient client, object args) { var settings = (Settings)args; RoundsManager.Of(client).MinimumPlayers = settings.MinimumPlayers; RoundsManager.Of(client).WaitTime = settings.WaitTime; RoundsManager.Of(client).FlyingPlayersCanPlay = settings.FlyingPlayersCanPlay; } public static bool LoadInto(BotBitsClient client, int minimumPlayers, int waitTime) { return LoadInto(client, new Settings(minimumPlayers, waitTime)); } } }
using System; using BotBits; namespace BotBitsExt.Rounds { public sealed class RoundsExtension : Extension<RoundsExtension> { private class Settings { public int MinimumPlayers { get; private set; } public int WaitTime { get; private set; } public bool FlyingPlayersCanPlay { get; private set; } public Settings(int minimumPlayers, int waitTime, bool flyingPlayersCanPlay = false) { MinimumPlayers = minimumPlayers; WaitTime = waitTime; FlyingPlayersCanPlay = flyingPlayersCanPlay; } } protected override void Initialize(BotBitsClient client, object args) { var settings = (Settings)args; RoundsManager.Of(client).MinimumPlayers = settings.MinimumPlayers; RoundsManager.Of(client).WaitTime = settings.WaitTime; RoundsManager.Of(client).FlyingPlayersCanPlay = settings.FlyingPlayersCanPlay; } public static bool LoadInto(BotBitsClient client, int minimumPlayers, int waitTime, bool flyingPlayersCanPlay = false) { return LoadInto(client, new Settings(minimumPlayers, waitTime, flyingPlayersCanPlay)); } } }
Fix using for Release build
using NLog; namespace Wox.Infrastructure.Logger { public class Log { private static NLog.Logger logger = LogManager.GetCurrentClassLogger(); public static void Error(System.Exception e) { #if DEBUG throw e; #else while (e.InnerException != null) { logger.Error(e.Message); logger.Error(e.StackTrace); e = e.InnerException; } #endif } public static void Debug(string msg) { System.Diagnostics.Debug.WriteLine($"DEBUG: {msg}"); logger.Debug(msg); } public static void Info(string msg) { System.Diagnostics.Debug.WriteLine($"INFO: {msg}"); logger.Info(msg); } public static void Warn(string msg) { System.Diagnostics.Debug.WriteLine($"WARN: {msg}"); logger.Warn(msg); } public static void Fatal(System.Exception e) { #if DEBUG throw e; #else logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); #endif } } }
using NLog; using Wox.Infrastructure.Exception; namespace Wox.Infrastructure.Logger { public class Log { private static NLog.Logger logger = LogManager.GetCurrentClassLogger(); public static void Error(System.Exception e) { #if DEBUG throw e; #else while (e.InnerException != null) { logger.Error(e.Message); logger.Error(e.StackTrace); e = e.InnerException; } #endif } public static void Debug(string msg) { System.Diagnostics.Debug.WriteLine($"DEBUG: {msg}"); logger.Debug(msg); } public static void Info(string msg) { System.Diagnostics.Debug.WriteLine($"INFO: {msg}"); logger.Info(msg); } public static void Warn(string msg) { System.Diagnostics.Debug.WriteLine($"WARN: {msg}"); logger.Warn(msg); } public static void Fatal(System.Exception e) { #if DEBUG throw e; #else logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); #endif } } }
Revert "Revert "Reacting to CLI breaking change""
// 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.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Graph; namespace Microsoft.DotNet.Watcher.Core.Internal { internal class Project : IProject { public Project(ProjectModel.Project runtimeProject) { ProjectFile = runtimeProject.ProjectFilePath; ProjectDirectory = runtimeProject.ProjectDirectory; Files = runtimeProject.Files.SourceFiles.Concat( runtimeProject.Files.ResourceFiles.Values.Concat( runtimeProject.Files.PreprocessSourceFiles.Concat( runtimeProject.Files.SharedFiles))).Concat( new string[] { runtimeProject.ProjectFilePath }) .ToList(); var projectLockJsonPath = Path.Combine(runtimeProject.ProjectDirectory, "project.lock.json"); if (File.Exists(projectLockJsonPath)) { var lockFile = LockFileReader.Read(projectLockJsonPath); ProjectDependencies = lockFile.ProjectLibraries.Select(dep => GetProjectRelativeFullPath(dep.Path)).ToList(); } else { ProjectDependencies = new string[0]; } } public IEnumerable<string> ProjectDependencies { get; private set; } public IEnumerable<string> Files { get; private set; } public string ProjectFile { get; private set; } public string ProjectDirectory { get; private set; } private string GetProjectRelativeFullPath(string path) { return Path.GetFullPath(Path.Combine(ProjectDirectory, path)); } } }
// 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.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Graph; namespace Microsoft.DotNet.Watcher.Core.Internal { internal class Project : IProject { public Project(ProjectModel.Project runtimeProject) { ProjectFile = runtimeProject.ProjectFilePath; ProjectDirectory = runtimeProject.ProjectDirectory; Files = runtimeProject.Files.SourceFiles.Concat( runtimeProject.Files.ResourceFiles.Values.Concat( runtimeProject.Files.PreprocessSourceFiles.Concat( runtimeProject.Files.SharedFiles))).Concat( new string[] { runtimeProject.ProjectFilePath }) .ToList(); var projectLockJsonPath = Path.Combine(runtimeProject.ProjectDirectory, "project.lock.json"); if (File.Exists(projectLockJsonPath)) { var lockFile = LockFileReader.Read(projectLockJsonPath, designTime: false); ProjectDependencies = lockFile.ProjectLibraries.Select(dep => GetProjectRelativeFullPath(dep.Path)).ToList(); } else { ProjectDependencies = new string[0]; } } public IEnumerable<string> ProjectDependencies { get; private set; } public IEnumerable<string> Files { get; private set; } public string ProjectFile { get; private set; } public string ProjectDirectory { get; private set; } private string GetProjectRelativeFullPath(string path) { return Path.GetFullPath(Path.Combine(ProjectDirectory, path)); } } }
Remove My Profile Page Menu Item Seed
using Portal.CMS.Entities.Entities; using System.Collections.Generic; using System.Linq; namespace Portal.CMS.Entities.Seed { public static class MenuSeed { public static void Seed(PortalEntityModel context) { if (!context.Menus.Any(x => x.MenuName == "Main Menu")) { var menuItems = new List<MenuItem>(); var authenticatedRole = context.Roles.First(x => x.RoleName == "Authenticated"); menuItems.Add(new MenuItem { LinkText = "Home", LinkURL = "/Home/Index", LinkIcon = "fa-home" }); menuItems.Add(new MenuItem { LinkText = "Blog", LinkURL = "/Blog/Read/Index", LinkIcon = "fa-book" }); context.Menus.Add(new MenuSystem { MenuName = "Main Menu", MenuItems = menuItems }); context.SaveChanges(); context.Menus.First(x => x.MenuName == "Main Menu").MenuItems.Add(new MenuItem { LinkText = "My Profile", LinkURL = "/MyProfile/Index", LinkIcon = "fa-user", MenuItemRoles = new List<MenuItemRole> { new MenuItemRole { RoleId = authenticatedRole.RoleId} } }); } } } }
using Portal.CMS.Entities.Entities; using System.Collections.Generic; using System.Linq; namespace Portal.CMS.Entities.Seed { public static class MenuSeed { public static void Seed(PortalEntityModel context) { if (!context.Menus.Any(x => x.MenuName == "Main Menu")) { var menuItems = new List<MenuItem>(); menuItems.Add(new MenuItem { LinkText = "Home", LinkURL = "/Home/Index", LinkIcon = "fa-home" }); menuItems.Add(new MenuItem { LinkText = "Blog", LinkURL = "/Blog/Read/Index", LinkIcon = "fa-book" }); context.Menus.Add(new MenuSystem { MenuName = "Main Menu", MenuItems = menuItems }); context.SaveChanges(); } } } }
Fix namespaces in ios interopconfig
/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ using System; namespace RealmNet { public static class InteropConfig { public static bool Is64Bit { #if REALM_32 get { Debug.Assert(IntPtr.Size == 4); return false; } #elif REALM_64 get { Debug.Assert(IntPtr.Size == 8); return true; } #else //if this is evaluated every time, a faster way could be implemented. Size is cost when we are running though so perhaps it gets inlined by the JITter get { return (IntPtr.Size == 8); } #endif } // This is always the "name" of the dll, regardless of bit-width. public const string DLL_NAME = "__Internal"; public static string GetDefaultDatabasePath() { const string dbFilename = "db.realm"; string libDir; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { libDir = NSFileManager.DefaultManager.GetUrls (NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User) [0].Path; } else { var docDir = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); libDir = System.IO.Path.GetFullPath(System.IO.Path.Combine (docDir, "..", "Library")); } return System.IO.Path.Combine(libDir, dbFilename); } } }
/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ using System; using UIKit; using Foundation; using System.IO; namespace RealmNet { public static class InteropConfig { public static bool Is64Bit { #if REALM_32 get { Debug.Assert(IntPtr.Size == 4); return false; } #elif REALM_64 get { Debug.Assert(IntPtr.Size == 8); return true; } #else //if this is evaluated every time, a faster way could be implemented. Size is cost when we are running though so perhaps it gets inlined by the JITter get { return (IntPtr.Size == 8); } #endif } // This is always the "name" of the dll, regardless of bit-width. public const string DLL_NAME = "__Internal"; public static string GetDefaultDatabasePath() { const string dbFilename = "db.realm"; string libDir; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { libDir = NSFileManager.DefaultManager.GetUrls (NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User) [0].Path; } else { var docDir = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); libDir = System.IO.Path.GetFullPath(System.IO.Path.Combine (docDir, "..", "Library")); } return Path.Combine(libDir, dbFilename); } } }
Add remark about failure scenarios
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api { internal interface IProjectSystemUpdateReferenceOperation { /// <summary> /// Applies a reference update operation to the project file. /// </summary> /// <returns>A boolean indicating success.</returns> Task<bool> ApplyAsync(); /// <summary> /// Reverts a reference update operation to the project file. /// </summary> /// <returns>A boolean indicating success.</returns> Task<bool> RevertAsync(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api { internal interface IProjectSystemUpdateReferenceOperation { /// <summary> /// Applies a reference update operation to the project file. /// </summary> /// <returns>A boolean indicating success.</returns> /// <remarks>Throws <see cref="InvalidOperationException"/> if operation has already been applied.</remarks> Task<bool> ApplyAsync(); /// <summary> /// Reverts a reference update operation to the project file. /// </summary> /// <returns>A boolean indicating success.</returns> /// <remarks>Throws <see cref="InvalidOperationException"/> if operation has not been applied.</remarks> Task<bool> RevertAsync(); } }
Add 'todo' to avoid type casting
namespace Sitecore.FakeDb.Serialization.Pipelines { using Sitecore.Data; using Sitecore.Data.Serialization.ObjectModel; using Sitecore.Diagnostics; using Sitecore.FakeDb.Pipelines; public class CopyParentId { public void Process(DsItemLoadingArgs args) { Assert.ArgumentNotNull(args, "args"); var syncItem = args.DsDbItem.SyncItem; Assert.ArgumentNotNull(syncItem, "SyncItem"); Assert.ArgumentCondition(ID.IsID(syncItem.ParentID), "ParentID", "Unable to copy ParentId. Valid identifier expected."); var parentId = ID.Parse(syncItem.ParentID); if (args.DataStorage.GetFakeItem(parentId) == null) { return; } ((DbItem)args.DsDbItem).ParentID = parentId; } } }
namespace Sitecore.FakeDb.Serialization.Pipelines { using Sitecore.Data; using Sitecore.Diagnostics; using Sitecore.FakeDb.Pipelines; public class CopyParentId { public void Process(DsItemLoadingArgs args) { Assert.ArgumentNotNull(args, "args"); var syncItem = args.DsDbItem.SyncItem; Assert.ArgumentNotNull(syncItem, "SyncItem"); Assert.ArgumentCondition(ID.IsID(syncItem.ParentID), "ParentID", "Unable to copy ParentId. Valid identifier expected."); var parentId = ID.Parse(syncItem.ParentID); if (args.DataStorage.GetFakeItem(parentId) == null) { return; } // TODO: Avoid type casting. ((DbItem)args.DsDbItem).ParentID = parentId; } } }
Solve bug henk import script
@{ ViewBag.Title = "Studenten importeren"; } <h2>Studenten importeren</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal">> <p>Kopieer het CSV bestand in het veld hieronder.</p> <textarea name="csv" id="csv" class="form-control"></textarea> </div> <div class="btn-group" style="margin-top: 15px"> <button type="submit" class="btn btn-primary">Importeren</button> </div> }
@{ ViewBag.Title = "Studenten importeren"; } <h2>Studenten importeren</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <p>Kopieer het CSV bestand in het veld hieronder.</p> <textarea name="csv" id="csv" class="form-control"></textarea> </div> <div class="btn-group" style="margin-top: 15px"> <button type="submit" class="btn btn-primary">Importeren</button> </div> }
Fix another issue where the word Hit wasn't highlighted from the start.
using Monaco; using Monaco.Editor; using Monaco.Languages; using System; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using Windows.Foundation; namespace MonacoEditorTestApp.Helpers { class EditorHoverProvider : HoverProvider { public IAsyncOperation<Hover> ProvideHover(IModel model, Position position) { return AsyncInfo.Run(async delegate (CancellationToken cancelationToken) { var word = await model.GetWordAtPositionAsync(position); if (word != null && word.Word != null && word.Word.IndexOf("Hit", 0, StringComparison.CurrentCultureIgnoreCase) != -1) { return new Hover(new string[] { "*Hit* - press the keys following together.", "Some **more** text is here.", "And a [link](https://www.github.com/)." }, new Range(position.LineNumber, position.Column, position.LineNumber, position.Column + 5)); } return default(Hover); }); } } }
using Monaco; using Monaco.Editor; using Monaco.Languages; using System; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using Windows.Foundation; namespace MonacoEditorTestApp.Helpers { class EditorHoverProvider : HoverProvider { public IAsyncOperation<Hover> ProvideHover(IModel model, Position position) { return AsyncInfo.Run(async delegate (CancellationToken cancelationToken) { var word = await model.GetWordAtPositionAsync(position); if (word != null && word.Word != null && word.Word.IndexOf("Hit", 0, StringComparison.CurrentCultureIgnoreCase) != -1) { return new Hover(new string[] { "*Hit* - press the keys following together.", "Some **more** text is here.", "And a [link](https://www.github.com/)." }, new Range(position.LineNumber, word.StartColumn, position.LineNumber, word.EndColumn)); } return default(Hover); }); } } }
Fix for Flowchart Enabled event handler coroutine issue
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { [EventHandlerInfo("", "Flowchart Enabled", "The block will execute when the Flowchart game object is enabled.")] [AddComponentMenu("")] public class FlowchartEnabled : EventHandler { protected virtual void OnEnable() { ExecuteBlock(); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { [EventHandlerInfo("", "Flowchart Enabled", "The block will execute when the Flowchart game object is enabled.")] [AddComponentMenu("")] public class FlowchartEnabled : EventHandler { protected virtual void OnEnable() { // Blocks use coroutines to schedule command execution, but Unity's coroutines are // sometimes unreliable when enabling / disabling objects. // To workaround this we execute the block on the next frame. Invoke("DoEvent", 0); } protected virtual void DoEvent() { ExecuteBlock(); } } }
Add missing namespace to Klawr script component template
using Klawr.ClrHost.Interfaces; using Klawr.UnrealEngine; namespace $RootNamespace$ { public class $ScriptName$ : UKlawrScriptComponent { public $ScriptName$(long instanceID, UObjectHandle nativeComponent) : base(instanceID, nativeComponent) { } } }
using Klawr.ClrHost.Interfaces; using Klawr.ClrHost.Managed.SafeHandles; using Klawr.UnrealEngine; namespace $RootNamespace$ { public class $ScriptName$ : UKlawrScriptComponent { public $ScriptName$(long instanceID, UObjectHandle nativeComponent) : base(instanceID, nativeComponent) { } } }
Use invariant culture for string comparisons
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace CsProjArrange { /// <summary> /// Compares a list of attributes in order by value. /// </summary> public class AttributeKeyComparer : IComparer<IEnumerable<XAttribute>> { public AttributeKeyComparer(IEnumerable<string> sortAttributes) { SortAttributes = sortAttributes; } public IEnumerable<string> SortAttributes { get; set; } public int Compare(IEnumerable<XAttribute> x, IEnumerable<XAttribute> y) { if (x == null) { if (y == null) { return 0; } return 1; } if (y == null) { return -1; } foreach (var attribute in SortAttributes) { string xValue = null; string yValue = null; var xAttribute = x.FirstOrDefault(a => a.Name.LocalName == attribute); var yAttribute = y.FirstOrDefault(a => a.Name.LocalName == attribute); if (xAttribute != null) { xValue = xAttribute.Value; } if (yAttribute != null) { yValue = yAttribute.Value; } int result = string.Compare(xValue ?? string.Empty, yValue ?? string.Empty); if (result != 0) { return result; } } return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace CsProjArrange { /// <summary> /// Compares a list of attributes in order by value. /// </summary> public class AttributeKeyComparer : IComparer<IEnumerable<XAttribute>> { public AttributeKeyComparer(IEnumerable<string> sortAttributes) { SortAttributes = sortAttributes; } public IEnumerable<string> SortAttributes { get; set; } public int Compare(IEnumerable<XAttribute> x, IEnumerable<XAttribute> y) { if (x == null) { if (y == null) { return 0; } return 1; } if (y == null) { return -1; } foreach (var attribute in SortAttributes) { string xValue = null; string yValue = null; var xAttribute = x.FirstOrDefault(a => a.Name.LocalName == attribute); var yAttribute = y.FirstOrDefault(a => a.Name.LocalName == attribute); if (xAttribute != null) { xValue = xAttribute.Value; } if (yAttribute != null) { yValue = yAttribute.Value; } int result = string.Compare(xValue ?? string.Empty, yValue ?? string.Empty, StringComparison.InvariantCulture); if (result != 0) { return result; } } return 0; } } }
Set IsEnabled wallet action property depending on wallet state
using WalletWasabi.Fluent.ViewModels.NavBar; using WalletWasabi.Helpers; namespace WalletWasabi.Fluent.ViewModels.Wallets.Actions { public abstract partial class WalletActionViewModel : NavBarItemViewModel { [AutoNotify] private bool _isEnabled; protected WalletActionViewModel(WalletViewModelBase wallet) { Wallet = Guard.NotNull(nameof(wallet), wallet); } public WalletViewModelBase Wallet { get; } public override string ToString() => Title; } }
using System.Reactive; using System.Reactive.Linq; using ReactiveUI; using WalletWasabi.Fluent.ViewModels.NavBar; using WalletWasabi.Helpers; using WalletWasabi.Wallets; namespace WalletWasabi.Fluent.ViewModels.Wallets.Actions { public abstract partial class WalletActionViewModel : NavBarItemViewModel { [AutoNotify] private bool _isEnabled; protected WalletActionViewModel(WalletViewModelBase wallet) { Wallet = Guard.NotNull(nameof(wallet), wallet); wallet.WhenAnyValue(x => x.WalletState).Select(x => IsEnabled = (x == WalletState.Started)); } public WalletViewModelBase Wallet { get; } public override string ToString() => Title; } }
Use extension method for string to float conversion
using System.Globalization; using System.Text; namespace SCPI.Acquire { public class ACQUIRE_SRATE : ICommand { public string Description => "Query the current sample rate. The default unit is Sa/s."; public float SampleRate { get; private set; } public string Command(params string[] parameters) => ":ACQuire:SRATe?"; public string HelpMessage() { var syntax = nameof(ACQUIRE_SRATE) + "\n"; var example = "Example: " + nameof(ACQUIRE_SRATE); return $"{syntax}\n{example}"; } public bool Parse(byte[] data) { if (data == null) { return false; } if (float.TryParse(Encoding.ASCII.GetString(data), NumberStyles.Any, CultureInfo.InvariantCulture, out float sampleRate)) { SampleRate = sampleRate; return true; } return false; } } }
using SCPI.Extensions; using System.Text; namespace SCPI.Acquire { public class ACQUIRE_SRATE : ICommand { public string Description => "Query the current sample rate. The default unit is Sa/s."; public float SampleRate { get; private set; } public string Command(params string[] parameters) => ":ACQuire:SRATe?"; public string HelpMessage() { var syntax = nameof(ACQUIRE_SRATE) + "\n"; var example = "Example: " + nameof(ACQUIRE_SRATE); return $"{syntax}\n{example}"; } public bool Parse(byte[] data) { if (data == null) { return false; } if (Encoding.ASCII.GetString(data).ScientificNotationStringToFloat(out float sampleRate)) { SampleRate = sampleRate; return true; } return false; } } }
Prepare for 1.0 BETA 2.
using ICities; using CitiesHarmony.API; namespace UOCRevisited { /// <summary> /// The base mod class for instantiation by the game. /// </summary> public class UOCRMod : IUserMod { // Public mod name and description. public string Name => ModName + " " + Version; public string Description => "Place as many roads with outside connections as you want"; // Internal and private name and version components. internal static string ModName => "Unlimited Outside Connections Revisited"; internal static string Version => BaseVersion + " " + Beta; internal static string Beta => "BETA 1"; private static string BaseVersion => "1.0"; /// <summary> /// Called by the game when the mod is enabled. /// </summary> public void OnEnabled() { // Apply Harmony patches via Cities Harmony. // Called here instead of OnCreated to allow the auto-downloader to do its work prior to launch. HarmonyHelper.DoOnHarmonyReady(() => Patcher.PatchAll()); } /// <summary> /// Called by the game when the mod is disabled. /// </summary> public void OnDisabled() { // Unapply Harmony patches via Cities Harmony. if (HarmonyHelper.IsHarmonyInstalled) { Patcher.UnpatchAll(); } } } }
using ICities; using CitiesHarmony.API; namespace UOCRevisited { /// <summary> /// The base mod class for instantiation by the game. /// </summary> public class UOCRMod : IUserMod { // Public mod name and description. public string Name => ModName + " " + Version; public string Description => "Place as many roads with outside connections as you want"; // Internal and private name and version components. internal static string ModName => "Unlimited Outside Connections Revisited"; internal static string Version => BaseVersion + " " + Beta; internal static string Beta => "BETA 2"; private static string BaseVersion => "1.0"; /// <summary> /// Called by the game when the mod is enabled. /// </summary> public void OnEnabled() { // Apply Harmony patches via Cities Harmony. // Called here instead of OnCreated to allow the auto-downloader to do its work prior to launch. HarmonyHelper.DoOnHarmonyReady(() => Patcher.PatchAll()); } /// <summary> /// Called by the game when the mod is disabled. /// </summary> public void OnDisabled() { // Unapply Harmony patches via Cities Harmony. if (HarmonyHelper.IsHarmonyInstalled) { Patcher.UnpatchAll(); } } } }
Add CORS for local testing
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using OpenStardriveServer.Domain.Database; using OpenStardriveServer.HostedServices; namespace OpenStardriveServer; public class Startup { public void ConfigureServices(IServiceCollection services) { DependencyInjectionConfig.ConfigureServices(services); services.AddSingleton(x => new SqliteDatabase { ConnectionString = $"Data Source=openstardrive-server.sqlite" }); services.AddControllers(); services.AddHostedService<ServerInitializationService>(); services.AddHostedService<CommandProcessingService>(); services.AddHostedService<ChronometerService>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using OpenStardriveServer.Domain.Database; using OpenStardriveServer.HostedServices; namespace OpenStardriveServer; public class Startup { public void ConfigureServices(IServiceCollection services) { DependencyInjectionConfig.ConfigureServices(services); services.AddSingleton(x => new SqliteDatabase { ConnectionString = $"Data Source=openstardrive-server.sqlite" }); services.AddControllers(); services.AddHostedService<ServerInitializationService>(); services.AddHostedService<CommandProcessingService>(); services.AddHostedService<ChronometerService>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().Build()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
Load the expected version from the assembly
namespace Raygun.Messages.Tests { using NUnit.Framework; using Shouldly; [TestFixture] public class RaygunClientMessageTests { [Test] public void Should_return_name_from_the_AssemblyTitleAttribute() { // Given var sut = SutFactory(); // When / Then sut.Name.ShouldBe("Raygun.Owin"); } [Test] public void Should_return_version_from_the_AssemblyVersionAttribute() { // Given var sut = SutFactory(); // When / Then sut.Version.ShouldBe("0.1.0.0"); } [Test] public void Should_return_client_url_for_the_github_repository() { // Given var sut = SutFactory(); // When / Then sut.ClientUrl.ShouldBe("https://github.com/xt0rted/Raygun.Owin"); } private static RaygunClientMessage SutFactory() { return new RaygunClientMessage(); } } }
namespace Raygun.Messages.Tests { using NUnit.Framework; using Shouldly; [TestFixture] public class RaygunClientMessageTests { [Test] public void Should_return_name_from_the_AssemblyTitleAttribute() { // Given var sut = SutFactory(); // When / Then sut.Name.ShouldBe("Raygun.Owin"); } [Test] public void Should_return_version_from_the_AssemblyVersionAttribute() { // Given var sut = SutFactory(); var expected = typeof (RaygunClient).Assembly.GetName().Version.ToString(); // When / Then sut.Version.ShouldBe(expected); } [Test] public void Should_return_client_url_for_the_github_repository() { // Given var sut = SutFactory(); // When / Then sut.ClientUrl.ShouldBe("https://github.com/xt0rted/Raygun.Owin"); } private static RaygunClientMessage SutFactory() { return new RaygunClientMessage(); } } }
Change http inflight requests default name to match Prometheus guidelines
namespace Prometheus.HttpExporter.AspNetCore.InFlight { public class HttpInFlightOptions : HttpExporterOptionsBase { public Gauge Gauge { get; set; } = Metrics.CreateGauge(DefaultName, DefaultHelp); private const string DefaultName = "aspnet_http_inflight"; private const string DefaultHelp = "Total number of requests currently being processed."; } }
namespace Prometheus.HttpExporter.AspNetCore.InFlight { public class HttpInFlightOptions : HttpExporterOptionsBase { public Gauge Gauge { get; set; } = Metrics.CreateGauge(DefaultName, DefaultHelp); private const string DefaultName = "http_executing_requests"; private const string DefaultHelp = "The number of requests currently being processed."; } }
Add item quality to schema items.
using Newtonsoft.Json; using SourceSchemaParser.JsonConverters; using System; using System.Collections.Generic; namespace SourceSchemaParser.Dota2 { public class DotaSchemaItem : SchemaItem { public DotaSchemaItemTool Tool { get; set; } [JsonProperty("tournament_url")] public string TournamentUrl { get; set; } [JsonProperty("image_banner")] public string ImageBannerPath { get; set; } [JsonProperty("item_rarity")] public string ItemRarity { get; set; } [JsonProperty("item_slot")] public string ItemSlot { get; set; } [JsonProperty("price_info")] public DotaSchemaItemPriceInfo PriceInfo { get; set; } [JsonConverter(typeof(DotaSchemaUsedByHeroesJsonConverter))] [JsonProperty("used_by_heroes")] public IList<string> UsedByHeroes { get; set; } } public class DotaSchemaItemPriceInfo { [JsonProperty("bucket")] public string Bucket { get; set; } [JsonProperty("class")] public string Class { get; set; } [JsonProperty("category_tags")] public string CategoryTags { get; set; } [JsonProperty("date")] public DateTime? Date { get; set; } [JsonConverter(typeof(DotaSchemaItemPriceJsonConverter))] [JsonProperty("price")] public decimal? Price { get; set; } [JsonConverter(typeof(StringToBoolJsonConverter))] [JsonProperty("is_pack_item")] public bool? IsPackItem { get; set; } } }
using Newtonsoft.Json; using SourceSchemaParser.JsonConverters; using System; using System.Collections.Generic; namespace SourceSchemaParser.Dota2 { public class DotaSchemaItem : SchemaItem { public DotaSchemaItemTool Tool { get; set; } [JsonProperty("tournament_url")] public string TournamentUrl { get; set; } [JsonProperty("image_banner")] public string ImageBannerPath { get; set; } [JsonProperty("item_rarity")] public string ItemRarity { get; set; } [JsonProperty("item_quality")] public string ItemQuality { get; set; } [JsonProperty("item_slot")] public string ItemSlot { get; set; } [JsonProperty("price_info")] public DotaSchemaItemPriceInfo PriceInfo { get; set; } [JsonConverter(typeof(DotaSchemaUsedByHeroesJsonConverter))] [JsonProperty("used_by_heroes")] public IList<string> UsedByHeroes { get; set; } } public class DotaSchemaItemPriceInfo { [JsonProperty("bucket")] public string Bucket { get; set; } [JsonProperty("class")] public string Class { get; set; } [JsonProperty("category_tags")] public string CategoryTags { get; set; } [JsonProperty("date")] public DateTime? Date { get; set; } [JsonConverter(typeof(DotaSchemaItemPriceJsonConverter))] [JsonProperty("price")] public decimal? Price { get; set; } [JsonConverter(typeof(StringToBoolJsonConverter))] [JsonProperty("is_pack_item")] public bool? IsPackItem { get; set; } } }
Add an entity get. and change old get to get key
using System; using System.Data; using System.Threading.Tasks; using Dapper.FastCrud; using Dapper.FastCrud.Configuration.StatementOptions.Builders; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; using Smooth.IoC.Dapper.Repository.UnitOfWork.Helpers; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public abstract partial class Repository<TSession, TEntity, TPk> where TEntity : class, IEntity<TPk> where TSession : ISession { public TEntity Get(TPk key, ISession session = null) { return GetAsync(key, session).Result; } public async Task<TEntity> GetAsync(TPk key, ISession session = null) { var entity = CreateInstanceHelper.Resolve<TEntity>(); entity.Id = key; if (session != null) { return await session.GetAsync(entity); } using (var uow = Factory.CreateSession<TSession>()) { return await uow.GetAsync(entity); } } protected async Task<TEntity> GetAsync(IDbConnection connection, TEntity keys, Action<ISelectSqlSqlStatementOptionsBuilder<TEntity>> statement) { if (connection != null) { return await connection.GetAsync(keys, statement); } using (var uow = Factory.CreateSession<TSession>()) { return await uow.GetAsync(keys, statement); } } } }
using System; using System.Data; using System.Threading.Tasks; using Dapper.FastCrud; using Dapper.FastCrud.Configuration.StatementOptions.Builders; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; using Smooth.IoC.Dapper.Repository.UnitOfWork.Helpers; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public abstract partial class Repository<TSession, TEntity, TPk> where TEntity : class, IEntity<TPk> where TSession : ISession { public TEntity GetKey(TPk key, ISession session = null) { return GetKeyAsync(key, session).Result; } public async Task<TEntity> GetKeyAsync(TPk key, ISession session = null) { var entity = CreateInstanceHelper.Resolve<TEntity>(); entity.Id = key; return await GetAsync(entity, session); } public TEntity Get(TEntity entity, ISession session = null) { return GetAsync(entity, session).Result; } public async Task<TEntity> GetAsync(TEntity entity, ISession session = null) { if (session != null) { return await session.GetAsync(entity); } using (var uow = Factory.CreateSession<TSession>()) { return await uow.GetAsync(entity); } } } }
Use correct extension for Android x64 folder
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using MICore; namespace AndroidDebugLauncher { internal static class TargetArchitectureExtensions { public static string ToNDKArchitectureName(this TargetArchitecture arch) { switch (arch) { case TargetArchitecture.X86: return "x86"; case TargetArchitecture.X64: return "x64"; case TargetArchitecture.ARM: return "arm"; case TargetArchitecture.ARM64: return "arm64"; default: Debug.Fail("Should be impossible"); throw new InvalidOperationException(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using MICore; namespace AndroidDebugLauncher { internal static class TargetArchitectureExtensions { public static string ToNDKArchitectureName(this TargetArchitecture arch) { switch (arch) { case TargetArchitecture.X86: return "x86"; case TargetArchitecture.X64: return "x86_64"; case TargetArchitecture.ARM: return "arm"; case TargetArchitecture.ARM64: return "arm64"; default: Debug.Fail("Should be impossible"); throw new InvalidOperationException(); } } } }
Add test cover for cancellable async query handling
using Bartender.Tests.Context; using Moq; using Xunit; namespace Bartender.Tests { public class CancellableAsyncQueryDispatcherTests : DispatcherTests { [Fact] public async void ShouldHandleQueryOnce_WhenCallDispatchAsyncMethod() { await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken); MockedCancellableAsyncQueryHandler.Verify(x => x.HandleAsync(It.IsAny<Query>(), CancellationToken), Times.Once); } } }
using Bartender.Tests.Context; using Moq; using Shouldly; using Xunit; namespace Bartender.Tests { public class CancellableAsyncQueryDispatcherTests : DispatcherTests { [Fact] public async void ShouldHandleQueryOnce_WhenCallDispatchAsyncMethod() { await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken); MockedCancellableAsyncQueryHandler.Verify(x => x.HandleAsync(It.IsAny<Query>(), CancellationToken), Times.Once); } [Fact] public async void ShouldReturnReadModel_WhenCallDispatchAsyncMethod() { var readModel = await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken); readModel.ShouldBeSameAs(ReadModel); } [Fact] public void ShouldThrowException_WhenNoAsyncQueryHandler() { MockedDependencyContainer .Setup(method => method.GetAllInstances<ICancellableAsyncQueryHandler<Query, ReadModel>>()) .Returns(() => new ICancellableAsyncQueryHandler<Query, ReadModel>[0]); Should .Throw<DispatcherException>(async () => await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken)) .Message .ShouldBe(NoHandlerExceptionMessageExpected); } [Fact] public void ShouldThrowException_WhenMultipleAsyncQueryHandler() { MockedDependencyContainer .Setup(method => method.GetAllInstances<ICancellableAsyncQueryHandler<Query, ReadModel>>()) .Returns(() => new [] { MockedCancellableAsyncQueryHandler.Object, MockedCancellableAsyncQueryHandler.Object }); Should .Throw<DispatcherException>(async () => await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken)) .Message .ShouldBe(MultipleHandlerExceptionMessageExpected); } } }
Remove active transactions metric no longer supplied by Seq 4
using System; using System.Collections.Generic; namespace Seq.Api.Model.Diagnostics { public class ServerMetricsEntity : Entity { public ServerMetricsEntity() { RunningTasks = new List<RunningTaskPart>(); } public double EventStoreDaysRecorded { get; set; } public double EventStoreDaysCached { get; set; } public int EventStoreEventsCached { get; set; } public DateTime? EventStoreFirstSegmentDateUtc { get; set; } public DateTime? EventStoreLastSegmentDateUtc { get; set; } public long EventStoreDiskRemainingBytes { get; set; } public int EndpointArrivalsPerMinute { get; set; } public int EndpointInfluxPerMinute { get; set; } public long EndpointIngestedBytesPerMinute { get; set; } public int EndpointInvalidPayloadsPerMinute { get; set; } public int EndpointUnauthorizedPayloadsPerMinute { get; set; } public TimeSpan ProcessUptime { get; set; } public long ProcessWorkingSetBytes { get; set; } public int ProcessThreads { get; set; } public int ProcessThreadPoolUserThreadsAvailable { get; set; } public int ProcessThreadPoolIocpThreadsAvailable { get; set; } public double SystemMemoryUtilization { get; set; } public List<RunningTaskPart> RunningTasks { get; set; } public int QueriesPerMinute { get; set; } public int QueryCacheTimeSliceHitsPerMinute { get; set; } public int QueryCacheInvalidationsPerMinute { get; set; } public int DocumentStoreActiveSessions { get; set; } public int DocumentStoreActiveTransactions { get; set; } } }
using System; using System.Collections.Generic; namespace Seq.Api.Model.Diagnostics { public class ServerMetricsEntity : Entity { public ServerMetricsEntity() { RunningTasks = new List<RunningTaskPart>(); } public double EventStoreDaysRecorded { get; set; } public double EventStoreDaysCached { get; set; } public int EventStoreEventsCached { get; set; } public DateTime? EventStoreFirstSegmentDateUtc { get; set; } public DateTime? EventStoreLastSegmentDateUtc { get; set; } public long EventStoreDiskRemainingBytes { get; set; } public int EndpointArrivalsPerMinute { get; set; } public int EndpointInfluxPerMinute { get; set; } public long EndpointIngestedBytesPerMinute { get; set; } public int EndpointInvalidPayloadsPerMinute { get; set; } public int EndpointUnauthorizedPayloadsPerMinute { get; set; } public TimeSpan ProcessUptime { get; set; } public long ProcessWorkingSetBytes { get; set; } public int ProcessThreads { get; set; } public int ProcessThreadPoolUserThreadsAvailable { get; set; } public int ProcessThreadPoolIocpThreadsAvailable { get; set; } public double SystemMemoryUtilization { get; set; } public List<RunningTaskPart> RunningTasks { get; set; } public int QueriesPerMinute { get; set; } public int QueryCacheTimeSliceHitsPerMinute { get; set; } public int QueryCacheInvalidationsPerMinute { get; set; } public int DocumentStoreActiveSessions { get; set; } } }
Make use of FluentAssertions in sanity unit test.
using Xunit; namespace Dcc.Test { public class DccMiddlewareTests { [Fact] public void SanityTest() { Assert.True(true); } } }
using FluentAssertions; using Xunit; namespace Dcc.Test { public class DccMiddlewareTests { [Fact] public void SanityTest() { true.Should().BeTrue(); } } }
Correct Administrators Role (set IsAdministrator to false)
using System; using Tralus.Framework.BusinessModel.Entities; namespace Tralus.Framework.Migration.Migrations { using System.Data.Entity.Migrations; public sealed class Configuration : TralusDbMigrationConfiguration<Data.FrameworkDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(Tralus.Framework.Data.FrameworkDbContext context) { base.Seed(context); // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // //var administratorRole = new Role(true) //{ // Name = "Administrators", // IsAdministrative = true, // CanEditModel = true, //}; context.Set<Role>().AddOrUpdate(new Role(true) { Id = new Guid("F011D97A-CDA4-46F4-BE33-B48C4CAB9A3E"), Name = "Administrators", IsAdministrative = true, CanEditModel = true, }); } } }
using System; using Tralus.Framework.BusinessModel.Entities; namespace Tralus.Framework.Migration.Migrations { using System.Data.Entity.Migrations; public sealed class Configuration : TralusDbMigrationConfiguration<Data.FrameworkDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(Tralus.Framework.Data.FrameworkDbContext context) { base.Seed(context); // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // //var administratorRole = new Role(true) //{ // Name = "Administrators", // IsAdministrative = true, // CanEditModel = true, //}; context.Set<Role>().AddOrUpdate(new Role(true) { Id = new Guid("F011D97A-CDA4-46F4-BE33-B48C4CAB9A3E"), Name = "Administrators", IsAdministrative = false, CanEditModel = true, }); } } }
Add new category - "Communications and media".
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CompetitionPlatform.Data.ProjectCategory; namespace CompetitionPlatform.Data.ProjectCategory { public class ProjectCategoriesRepository : IProjectCategoriesRepository { public List<string> GetCategories() { return new List<string> { "Finance", "Technology", "Bitcoin", "Mobile", "Payments" }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CompetitionPlatform.Data.ProjectCategory; namespace CompetitionPlatform.Data.ProjectCategory { public class ProjectCategoriesRepository : IProjectCategoriesRepository { public List<string> GetCategories() { return new List<string> { "Finance", "Technology", "Bitcoin", "Mobile", "Payments", "Communications and media" }; } } }
Add SA1008 tests for ref expressions
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.SpacingRules { using Test.SpacingRules; public class SA1008CSharp7UnitTests : SA1008UnitTests { } }
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.SpacingRules { using System.Threading; using System.Threading.Tasks; using StyleCop.Analyzers.Test.SpacingRules; using TestHelper; using Xunit; using static StyleCop.Analyzers.SpacingRules.SA1008OpeningParenthesisMustBeSpacedCorrectly; public class SA1008CSharp7UnitTests : SA1008UnitTests { /// <summary> /// Verifies that spacing for <c>ref</c> expressions is handled properly. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestRefExpressionAsync() { var testCode = @"namespace TestNamespace { using System.Threading.Tasks; public class TestClass { public void TestMethod() { int test = 1; ref int t = ref( test); } } } "; var fixedCode = @"namespace TestNamespace { using System.Threading.Tasks; public class TestClass { public void TestMethod() { int test = 1; ref int t = ref (test); } } } "; DiagnosticResult[] expectedDiagnostics = { this.CSharpDiagnostic(DescriptorPreceded).WithLocation(10, 28), this.CSharpDiagnostic(DescriptorNotFollowed).WithLocation(10, 28), }; await this.VerifyCSharpDiagnosticAsync(testCode, expectedDiagnostics, CancellationToken.None).ConfigureAwait(false); await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); await this.VerifyCSharpFixAsync(testCode, fixedCode, numberOfFixAllIterations: 2).ConfigureAwait(false); } } }
Rename Enumerable.Equals(object, object, Type) to ItemsEqual, for clarity of purpose.
namespace Fixie.Assertions { using System; using System.Collections; class EnumerableEqualityComparer { public bool EnumerableEqual(IEnumerable x, IEnumerable y) { var enumeratorX = x.GetEnumerator(); var enumeratorY = y.GetEnumerator(); while (true) { bool hasNextX = enumeratorX.MoveNext(); bool hasNextY = enumeratorY.MoveNext(); if (!hasNextX || !hasNextY) return hasNextX == hasNextY; if (enumeratorX.Current != null || enumeratorY.Current != null) { if (enumeratorX.Current != null && enumeratorY.Current == null) return false; if (enumeratorX.Current == null) return false; var xType = enumeratorX.Current.GetType(); var yType = enumeratorY.Current.GetType(); if (xType.IsAssignableFrom(yType)) { if (!Equals(enumeratorX.Current, enumeratorY.Current, xType)) return false; } else if (yType.IsAssignableFrom(xType)) { if (!Equals(enumeratorY.Current, enumeratorX.Current, yType)) return false; } else { return false; } } } } static bool Equals(object a, object b, Type baseType) { var assertComparerType = typeof(AssertEqualityComparer); var equal = assertComparerType.GetMethod("Equal"); var specificEqual = equal.MakeGenericMethod(baseType); return (bool)specificEqual.Invoke(null, new[] { a, b }); } } }
namespace Fixie.Assertions { using System; using System.Collections; class EnumerableEqualityComparer { public bool EnumerableEqual(IEnumerable x, IEnumerable y) { var enumeratorX = x.GetEnumerator(); var enumeratorY = y.GetEnumerator(); while (true) { bool hasNextX = enumeratorX.MoveNext(); bool hasNextY = enumeratorY.MoveNext(); if (!hasNextX || !hasNextY) return hasNextX == hasNextY; if (enumeratorX.Current != null || enumeratorY.Current != null) { if (enumeratorX.Current != null && enumeratorY.Current == null) return false; if (enumeratorX.Current == null) return false; var xType = enumeratorX.Current.GetType(); var yType = enumeratorY.Current.GetType(); if (xType.IsAssignableFrom(yType)) { if (!ItemsEqual(enumeratorX.Current, enumeratorY.Current, xType)) return false; } else if (yType.IsAssignableFrom(xType)) { if (!ItemsEqual(enumeratorY.Current, enumeratorX.Current, yType)) return false; } else { return false; } } } } static bool ItemsEqual(object a, object b, Type baseType) { var assertComparerType = typeof(AssertEqualityComparer); var equal = assertComparerType.GetMethod("Equal"); var specificEqual = equal.MakeGenericMethod(baseType); return (bool)specificEqual.Invoke(null, new[] { a, b }); } } }
Update TecSupportService1 with the new parameter list.
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using DbAndRepository; using DbAndRepository.IRepositories; using DbAndRepository.Repostirories; namespace TechSupportService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TechSupportService1" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select TechSupportService1.svc or TechSupportService1.svc.cs at the Solution Explorer and start debugging. public class TechSupportService1 : ITechSupportService1 { private ILoginDataRepository Auth; public TechSupportService1() { TechSupportDatabaseEntities1 d=new TechSupportDatabaseEntities1(); Auth=new LoginDataRepository(d); } public LoginResult Login(string username, string password) { string name = ""; bool a= Auth.Authenticate(username, password,out name); return new LoginResult() {Role = "",Valid = a}; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using DbAndRepository; using DbAndRepository.IRepositories; using DbAndRepository.Repostirories; namespace TechSupportService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TechSupportService1" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select TechSupportService1.svc or TechSupportService1.svc.cs at the Solution Explorer and start debugging. public class TechSupportService1 : ITechSupportService1 { private ILoginDataRepository Auth; public TechSupportService1() { TechSupportDatabaseEntities d = new TechSupportDatabaseEntities(); Auth = new LoginDataRepository(d); } public LoginResult Login(string username, string password) { string name = string.Empty, role = string.Empty; bool a= Auth.Authenticate(username, password,out name, out role); return new LoginResult() { Role = role, Valid = a }; } } }
Fix error when turning visual debugging on/off in Unity 5.4 or newer
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; namespace Entitas.Unity { public class ScriptingDefineSymbols { public Dictionary<BuildTargetGroup, string> buildTargetToDefSymbol { get { return _buildTargetToDefSymbol; } } readonly Dictionary<BuildTargetGroup, string> _buildTargetToDefSymbol; public ScriptingDefineSymbols() { _buildTargetToDefSymbol = Enum.GetValues(typeof(BuildTargetGroup)) .Cast<BuildTargetGroup>() .Where(buildTargetGroup => buildTargetGroup != BuildTargetGroup.Unknown) .Distinct() .ToDictionary( buildTargetGroup => buildTargetGroup, buildTargetGroup => PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup) ); } public void AddDefineSymbol(string defineSymbol) { foreach(var kv in _buildTargetToDefSymbol) { PlayerSettings.SetScriptingDefineSymbolsForGroup( kv.Key, kv.Value.Replace(defineSymbol, string.Empty) + "," + defineSymbol ); } } public void RemoveDefineSymbol(string defineSymbol) { foreach(var kv in _buildTargetToDefSymbol) { PlayerSettings.SetScriptingDefineSymbolsForGroup( kv.Key, kv.Value.Replace(defineSymbol, string.Empty) ); } } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; namespace Entitas.Unity { public class ScriptingDefineSymbols { public Dictionary<BuildTargetGroup, string> buildTargetToDefSymbol { get { return _buildTargetToDefSymbol; } } readonly Dictionary<BuildTargetGroup, string> _buildTargetToDefSymbol; public ScriptingDefineSymbols() { _buildTargetToDefSymbol = Enum.GetValues(typeof(BuildTargetGroup)) .Cast<BuildTargetGroup>() .Where(buildTargetGroup => buildTargetGroup != BuildTargetGroup.Unknown) .Where(buildTargetGroup => !isBuildTargetObsolete(buildTargetGroup)) .Distinct() .ToDictionary( buildTargetGroup => buildTargetGroup, buildTargetGroup => PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup) ); } public void AddDefineSymbol(string defineSymbol) { foreach(var kv in _buildTargetToDefSymbol) { PlayerSettings.SetScriptingDefineSymbolsForGroup( kv.Key, kv.Value.Replace(defineSymbol, string.Empty) + "," + defineSymbol ); } } public void RemoveDefineSymbol(string defineSymbol) { foreach(var kv in _buildTargetToDefSymbol) { PlayerSettings.SetScriptingDefineSymbolsForGroup( kv.Key, kv.Value.Replace(defineSymbol, string.Empty) ); } } bool isBuildTargetObsolete(BuildTargetGroup value) { var fieldInfo = value.GetType().GetField(value.ToString()); var attributes = (ObsoleteAttribute[])fieldInfo.GetCustomAttributes(typeof(ObsoleteAttribute), false); return (attributes != null && attributes.Length > 0); } } }
Use OneTimeSetUp instead of TestFixtureSetUp.
namespace ForecastPCL.Test { using System; using System.Configuration; using System.Threading.Tasks; using DarkSkyApi; using NUnit.Framework; [TestFixture] public class LanguageTests { // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; /// <summary> /// API key to be used for testing. This should be specified in the /// test project's app.config file. /// </summary> private string apiKey; /// <summary> /// Sets up all tests by retrieving the API key from app.config. /// </summary> [TestFixtureSetUp] public void SetUp() { apiKey = ConfigurationManager.AppSettings["ApiKey"]; } [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } [Test] public async Task UnicodeLanguageIsSupported() { var client = new ForecastApi(apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese); Assert.That(result, Is.Not.Null); } } }
namespace ForecastPCL.Test { using System; using System.Configuration; using System.Threading.Tasks; using DarkSkyApi; using NUnit.Framework; [TestFixture] public class LanguageTests { // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; /// <summary> /// API key to be used for testing. This should be specified in the /// test project's app.config file. /// </summary> private string apiKey; /// <summary> /// Sets up all tests by retrieving the API key from app.config. /// </summary> [OneTimeSetUp] public void SetUp() { apiKey = ConfigurationManager.AppSettings["ApiKey"]; } [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } [Test] public async Task UnicodeLanguageIsSupported() { var client = new ForecastApi(apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese); Assert.That(result, Is.Not.Null); } } }
Fix build for versions without Assembly.Location
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; using System.Reflection; using Xunit; namespace System.Net.NameResolution.Tests { public static class LoggingTest { [Fact] public static void EventSource_ExistsWithCorrectId() { Type esType = typeof(Dns).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false); Assert.NotNull(esType); Assert.Equal("Microsoft-System-Net-NameResolution", EventSource.GetName(esType)); Assert.Equal(Guid.Parse("5f302add-3825-520e-8fa0-627b206e2e7e"), EventSource.GetGuid(esType)); Assert.NotEmpty(EventSource.GenerateManifest(esType, esType.GetTypeInfo().Assembly.Location)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; using System.Reflection; using Xunit; namespace System.Net.NameResolution.Tests { public static class LoggingTest { [Fact] public static void EventSource_ExistsWithCorrectId() { Type esType = typeof(Dns).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false); Assert.NotNull(esType); Assert.Equal("Microsoft-System-Net-NameResolution", EventSource.GetName(esType)); Assert.Equal(Guid.Parse("5f302add-3825-520e-8fa0-627b206e2e7e"), EventSource.GetGuid(esType)); Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest")); } } }
Update remove route to correct value
namespace SFA.DAS.EmployerAccounts.Web.Authorization { public static class AuthorizationConstants { public const string Tier2User = "Tier2User"; public const string TeamViewRoute = "accounts/{hashedaccountid}/teams/view"; public const string TeamRoute = "accounts/{hashedaccountid}/teams"; public const string TeamInvite = "accounts/{hashedaccountid}/teams/invite"; public const string TeamInviteComplete = "accounts/{hashedaccountid}/teams/invite/next"; public const string TeamMemberRemove = "accounts/{hashedaccountid}/teams/remove"; public const string TeamReview = "accounts/{hashedaccountid}/teams/{email}/review"; public const string TeamMemberRoleChange = "accounts/{hashedaccountid}/teams/{email}/role/change"; public const string TeamMemberInviteResend = "accounts/{hashedaccountid}/teams/resend"; public const string TeamMemberInviteCancel = "accounts/{hashedaccountid}/teams/{invitationId}/cancel"; } }
namespace SFA.DAS.EmployerAccounts.Web.Authorization { public static class AuthorizationConstants { public const string Tier2User = "Tier2User"; public const string TeamViewRoute = "accounts/{hashedaccountid}/teams/view"; public const string TeamRoute = "accounts/{hashedaccountid}/teams"; public const string TeamInvite = "accounts/{hashedaccountid}/teams/invite"; public const string TeamInviteComplete = "accounts/{hashedaccountid}/teams/invite/next"; public const string TeamMemberRemove = "accounts/{hashedaccountid}/teams/{email}/remove"; public const string TeamReview = "accounts/{hashedaccountid}/teams/{email}/review"; public const string TeamMemberRoleChange = "accounts/{hashedaccountid}/teams/{email}/role/change"; public const string TeamMemberInviteResend = "accounts/{hashedaccountid}/teams/resend"; public const string TeamMemberInviteCancel = "accounts/{hashedaccountid}/teams/{invitationId}/cancel"; } }
Make Log4NetLevel enricher internal - no need for it to be public
using Serilog.Core; using Serilog.Events; namespace Umbraco.Core.Logging.SerilogExtensions { /// <summary> /// This is used to create a new property in Logs called 'Log4NetLevel' /// So that we can map Serilog levels to Log4Net levels - so log files stay consistent /// </summary> public class Log4NetLevelMapperEnricher : ILogEventEnricher { public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { var log4NetLevel = string.Empty; switch (logEvent.Level) { case LogEventLevel.Debug: log4NetLevel = "DEBUG"; break; case LogEventLevel.Error: log4NetLevel = "ERROR"; break; case LogEventLevel.Fatal: log4NetLevel = "FATAL"; break; case LogEventLevel.Information: log4NetLevel = "INFO"; break; case LogEventLevel.Verbose: log4NetLevel = "ALL"; break; case LogEventLevel.Warning: log4NetLevel = "WARN"; break; } //Pad string so that all log levels are 5 chars long (needed to keep the txt log file lined up nicely) log4NetLevel = log4NetLevel.PadRight(5); logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Log4NetLevel", log4NetLevel)); } } }
using Serilog.Core; using Serilog.Events; namespace Umbraco.Core.Logging.SerilogExtensions { /// <summary> /// This is used to create a new property in Logs called 'Log4NetLevel' /// So that we can map Serilog levels to Log4Net levels - so log files stay consistent /// </summary> internal class Log4NetLevelMapperEnricher : ILogEventEnricher { public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { var log4NetLevel = string.Empty; switch (logEvent.Level) { case LogEventLevel.Debug: log4NetLevel = "DEBUG"; break; case LogEventLevel.Error: log4NetLevel = "ERROR"; break; case LogEventLevel.Fatal: log4NetLevel = "FATAL"; break; case LogEventLevel.Information: log4NetLevel = "INFO"; break; case LogEventLevel.Verbose: log4NetLevel = "ALL"; break; case LogEventLevel.Warning: log4NetLevel = "WARN"; break; } //Pad string so that all log levels are 5 chars long (needed to keep the txt log file lined up nicely) log4NetLevel = log4NetLevel.PadRight(5); logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Log4NetLevel", log4NetLevel)); } } }
Add SSL option to Rabbit sample
using System.Text; using Microsoft.AspNetCore.Mvc; using RabbitMQ.Client; namespace Rabbit.Controllers { public class RabbitController : Controller { ConnectionFactory _rabbitConnection; public RabbitController([FromServices] ConnectionFactory rabbitConnection) { _rabbitConnection = rabbitConnection; } public IActionResult Receive() { using (var connection = _rabbitConnection.CreateConnection()) using (var channel = connection.CreateModel()) { CreateQueue(channel); var data = channel.BasicGet("rabbit-test", true); if (data != null) { ViewData["message"] = Encoding.UTF8.GetString(data.Body); } } return View(); } public IActionResult Send(string message) { if (message != null && message != "") { using (var connection = _rabbitConnection.CreateConnection()) using (var channel = connection.CreateModel()) { CreateQueue(channel); var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: "rabbit-test", basicProperties: null, body: body); } } return View(); } protected void CreateQueue(IModel channel) { channel.QueueDeclare(queue: "rabbit-test", durable: false, exclusive: false, autoDelete: false, arguments: null); } } }
using System.Text; using Microsoft.AspNetCore.Mvc; using RabbitMQ.Client; #if SSL using System.Security.Authentication; using System.Net.Security; #endif namespace Rabbit.Controllers { public class RabbitController : Controller { ConnectionFactory _rabbitConnection; public RabbitController([FromServices] ConnectionFactory rabbitConnection) { _rabbitConnection = rabbitConnection; #if SSL SslOption opt = new SslOption(); opt.Version = SslProtocols.Tls12; opt.Enabled = true; // Only needed if want to disable certificate validations //opt.AcceptablePolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors | // SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable; _rabbitConnection.Ssl = opt; #endif } public IActionResult Receive() { using (var connection = _rabbitConnection.CreateConnection()) using (var channel = connection.CreateModel()) { CreateQueue(channel); var data = channel.BasicGet("rabbit-test", true); if (data != null) { ViewData["message"] = Encoding.UTF8.GetString(data.Body); } } return View(); } public IActionResult Send(string message) { if (message != null && message != "") { using (var connection = _rabbitConnection.CreateConnection()) using (var channel = connection.CreateModel()) { CreateQueue(channel); var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: "rabbit-test", basicProperties: null, body: body); } } return View(); } protected void CreateQueue(IModel channel) { channel.QueueDeclare(queue: "rabbit-test", durable: false, exclusive: false, autoDelete: false, arguments: null); } } }
Use ReactiveUI Events for Data Context Changed
using Ets.Mobile.ViewModel.Contracts.Settings; using System; using System.Reactive.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using ReactiveUI; using System.Reactive.Concurrency; namespace Ets.Mobile.Content.Settings { public sealed partial class Options : UserControl { public Options() { InitializeComponent(); this.Events().DataContextChanged.Subscribe(args => { var options = args.NewValue as IOptionsViewModel; if (options != null) { options.HandleScheduleBackgroundService.IsExecuting.Subscribe(isExecuting => { ShowSchedule.IsEnabled = !isExecuting; LoadingShowScheduleChanged.Visibility = isExecuting ? Visibility.Visible : Visibility.Collapsed; }); } }); } } }
using Ets.Mobile.ViewModel.Contracts.Settings; using System; using System.Reactive.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Ets.Mobile.Content.Settings { public sealed partial class Options : UserControl { public Options() { InitializeComponent(); this.Events().DataContextChanged.Subscribe(args => { var options = args.NewValue as IOptionsViewModel; if (options != null) { options.HandleScheduleBackgroundService.IsExecuting.Subscribe(isExecuting => { ShowSchedule.IsEnabled = !isExecuting; LoadingShowScheduleChanged.Visibility = isExecuting ? Visibility.Visible : Visibility.Collapsed; }); } }); } } }
Add scripts that make HTML5, CSS and JavaScript work in Internet Explorer 8 and lower
<!DOCTYPE html> <html> <head> <title>Zaaikalender | @ViewBag.Title</title> <link rel="stylesheet" href="/Content/Stylesheets/responsive-square-elements.css"> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="/Scripts/flowtype.js"></script> <script src="/Scripts/font-settings.js"></script> </head> <body> <div class="container"> @RenderBody() </div> </body> </html>
<!DOCTYPE html> <html> <head> <title>Zaaikalender | @ViewBag.Title</title> <link rel="stylesheet" href="/Content/Stylesheets/responsive-square-elements.css"> <!--[if lte IE 8]> <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/4.0.3/es5-shim.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv-printshiv.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="/Scripts/flowtype.js"></script> <script src="/Scripts/font-settings.js"></script> <script src="/Scripts/month-click-listeners.js"></script> </head> <body> <div class="container"> @RenderBody() </div> </body> </html>
Tweak Stylesheet Link writing in XMlDomExtenstions
using System.Xml; namespace Palaso.Xml { public static class XmlDomExtensions { public static XmlDocument StripXHtmlNameSpace(this XmlDocument node) { XmlDocument x = new XmlDocument(); x.LoadXml(node.OuterXml.Replace("xmlns", "xmlnsNeutered")); return x; } public static void AddStyleSheet(this XmlDocument dom, string cssFilePath) { var head = dom.SelectSingleNodeHonoringDefaultNS("//head"); AddSheet(dom, head, cssFilePath); } private static void AddSheet(this XmlDocument dom, XmlNode head, string cssFilePath) { var link = dom.CreateElement("link", "http://www.w3.org/1999/xhtml"); link.SetAttribute("rel", "stylesheet"); link.SetAttribute("href", "file://" + cssFilePath); link.SetAttribute("type", "text/css"); head.AppendChild(link); } } }
using System; using System.IO; using System.Xml; namespace Palaso.Xml { public static class XmlDomExtensions { public static XmlDocument StripXHtmlNameSpace(this XmlDocument node) { XmlDocument x = new XmlDocument(); x.LoadXml(node.OuterXml.Replace("xmlns", "xmlnsNeutered")); return x; } public static void AddStyleSheet(this XmlDocument dom, string cssFilePath) { var head = dom.SelectSingleNodeHonoringDefaultNS("//head"); AddSheet(dom, head, cssFilePath); } private static void AddSheet(this XmlDocument dom, XmlNode head, string cssFilePath) { var link = dom.CreateElement("link", "http://www.w3.org/1999/xhtml"); link.SetAttribute("rel", "stylesheet"); if(cssFilePath.Contains(Path.PathSeparator.ToString())) // review: not sure about relative vs. complete paths { link.SetAttribute("href", "file://" + cssFilePath); } else //at least with gecko/firefox, something like "file://foo.css" is never found, so just give it raw { link.SetAttribute("href",cssFilePath); } link.SetAttribute("type", "text/css"); head.AppendChild(link); } } }
Remove RandomTrace stuff from main
using static System.Console; using CIV.Ccs; using CIV.Interfaces; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { WriteLine(action); } } } }
using static System.Console; using System.Linq; using CIV.Ccs; using CIV.Hml; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)"; var prova = HmlFacade.ParseAll(hmlText); WriteLine(prova.Check(processes["Prison"])); } } }
Fix command line error display
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CommandLine; using Meraki; namespace Meraki.Console { class Program { static void Main(string[] args) { try { Parser.Default.ParseArguments<LabOptions, DumpOptions>(args) .WithParsed<LabOptions>(clo => new CiscoLearningLab().Run(clo.ApiKey).Wait()) .WithParsed<DumpOptions>(clo => new Dump().Run(clo.ApiKey).Wait()) .WithNotParsed(errors => System.Console.Error.WriteLine("InvalidArgs")); } catch (Exception ex) { System.Console.Error.WriteLine(ex); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CommandLine; using Meraki; namespace Meraki.Console { class Program { static void Main(string[] args) { try { Parser.Default.ParseArguments<LabOptions, DumpOptions>(args) .WithParsed<LabOptions>(clo => new CiscoLearningLab().Run(clo.ApiKey).Wait()) .WithParsed<DumpOptions>(clo => new Dump().Run(clo.ApiKey).Wait()); } catch (Exception ex) { System.Console.Error.WriteLine(ex); } } } }
Add heading to report result class
using System.Dynamic; namespace KenticoInspector.Core.Models { public class ReportResults { public ReportResults() { Data = new ExpandoObject(); } public dynamic Data { get; set; } public string Status { get; set; } public string Summary { get; set; } public string Type { get; set; } } }
using System.Dynamic; namespace KenticoInspector.Core.Models { public class ReportResults { public ReportResults() { Data = new ExpandoObject(); } public dynamic Data { get; set; } public string Heading { get; set; } public string Status { get; set; } public string Summary { get; set; } public string Type { get; set; } } }
Add namespace brackets - because of teamcity
using System.Collections.Generic; namespace Arkivverket.Arkade.Core.Util.FileFormatIdentification; public interface IFileFormatInfoFilesGenerator { void Generate(IEnumerable<IFileFormatInfo> fileFormatInfoSet, string relativePathRoot, string resultFileFullPath); }
using System.Collections.Generic; namespace Arkivverket.Arkade.Core.Util.FileFormatIdentification { public interface IFileFormatInfoFilesGenerator { void Generate(IEnumerable<IFileFormatInfo> fileFormatInfoSet, string relativePathRoot, string resultFileFullPath); } }
Set the column width to resize when the listview resizes
using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PathViewer { public partial class FormPathViewer : Form { public FormPathViewer() { InitializeComponent(); LoadPaths(); } private void LoadPaths() { // Get the PATH from the registery string regKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\"; string regValue = (string)Registry.LocalMachine.OpenSubKey(regKey).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames); // Split the string var paths = regValue.Split(';'); // Display them foreach(var i in paths) { lvPaths.Items.Add(i); } } } }
using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PathViewer { public partial class FormPathViewer : Form { public FormPathViewer() { InitializeComponent(); LoadPaths(); } private void LoadPaths() { // Get the PATH from the registery string regKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\"; string regValue = (string)Registry.LocalMachine.OpenSubKey(regKey).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames); // Split the string var paths = regValue.Split(';'); // Display them foreach(var i in paths) { lvPaths.Items.Add(i); } } // Have the column width match the listview width private void lvPaths_Resize(object sender, EventArgs e) { lvPaths.Columns[0].Width = lvPaths.Width; } } }
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.Moq")] [assembly: AssemblyDescription("")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.Moq")]
Use system highlight color in game list selection
using System.Drawing; using System.Windows.Forms; using BrightIdeasSoftware; namespace SteamGames { internal sealed class GameRenderer : AbstractRenderer { private readonly StringFormat sf; public GameRenderer() { sf = new StringFormat(StringFormat.GenericTypographic); sf.Alignment = StringAlignment.Center; sf.Trimming = StringTrimming.EllipsisWord; } public override bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object rowObject) { if (e.Item.ListView.SelectedItems.Contains(e.Item)) { g.FillRectangle(Brushes.RoyalBlue, itemBounds); } else { g.FillRectangle(Brushes.Black, itemBounds); } var game = (Game) rowObject; if (game.Logo != null) { g.DrawImage(game.Logo, new Rectangle(itemBounds.Location, new Size(184, 69))); } g.DrawString(game.Name, e.Item.Font, Brushes.White, new RectangleF(itemBounds.X, itemBounds.Y + 69, 184, 30), sf); return true; } } }
using System.Drawing; using System.Windows.Forms; using BrightIdeasSoftware; namespace SteamGames { internal sealed class GameRenderer : AbstractRenderer { private readonly StringFormat sf; private Brush SelectionBrush = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight)); public GameRenderer() { sf = new StringFormat(StringFormat.GenericTypographic); sf.Alignment = StringAlignment.Center; sf.Trimming = StringTrimming.EllipsisWord; } public override bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object rowObject) { if (e.Item.ListView.SelectedItems.Contains(e.Item)) { g.FillRectangle(SelectionBrush, itemBounds); } else { g.FillRectangle(Brushes.Black, itemBounds); } var game = (Game) rowObject; if (game.Logo != null) { g.DrawImage(game.Logo, new Rectangle(itemBounds.Location, new Size(184, 69))); } g.DrawString(game.Name, e.Item.Font, Brushes.White, new RectangleF(itemBounds.X, itemBounds.Y + 69, 184, 30), sf); return true; } } }
Make room setting's BeatmapID non-nullable
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using osu.Game.Online.API; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings> { public int? BeatmapID { get; set; } public int? RulesetID { get; set; } public string Name { get; set; } = "Unnamed room"; [NotNull] public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>(); public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal); public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using osu.Game.Online.API; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings> { public int BeatmapID { get; set; } public int? RulesetID { get; set; } public string Name { get; set; } = "Unnamed room"; [NotNull] public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>(); public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal); public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}"; } }
Update existing documentation for list ids.
namespace TraktApiSharp.Objects.Get.Users.Lists { using Newtonsoft.Json; using System.Globalization; /// <summary> /// A collection of ids for various web services for a Trakt list. /// </summary> public class TraktListIds { /// <summary> /// The Trakt numeric id for the list. /// </summary> [JsonProperty(PropertyName = "trakt")] public int Trakt { get; set; } /// <summary> /// The Trakt slug for the list. /// </summary> [JsonProperty(PropertyName = "slug")] public string Slug { get; set; } /// <summary> /// Tests, if at least one id has been set. /// </summary> [JsonIgnore] public bool HasAnyId => Trakt > 0 || !string.IsNullOrEmpty(Slug); /// <summary> /// Get the most reliable id from those that have been set for the list. /// </summary> /// <returns>The id as a string.</returns> public string GetBestId() { if (Trakt > 0) return Trakt.ToString(CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(Slug)) return Slug; return string.Empty; } } }
namespace TraktApiSharp.Objects.Get.Users.Lists { using Newtonsoft.Json; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt list.</summary> public class TraktListIds { /// <summary>Gets or sets the Trakt numeric id.</summary> [JsonProperty(PropertyName = "trakt")] public int Trakt { get; set; } /// <summary>Gets or sets the Trakt slug.</summary> [JsonProperty(PropertyName = "slug")] public string Slug { get; set; } /// <summary>Returns, whether any id has been set.</summary> [JsonIgnore] public bool HasAnyId => Trakt > 0 || !string.IsNullOrEmpty(Slug); /// <summary>Gets the most reliable id from those that have been set.</summary> /// <returns>The id as a string or an empty string, if no id is set.</returns> public string GetBestId() { if (Trakt > 0) return Trakt.ToString(); if (!string.IsNullOrEmpty(Slug)) return Slug; return string.Empty; } } }
Use a type converter to try and convert values
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Internals.Mapping { using System; using Reflection; public class NullableValueObjectMapper<T, TValue> : IObjectMapper<T> where TValue : struct { readonly ReadWriteProperty<T> _property; public NullableValueObjectMapper(ReadWriteProperty<T> property) { _property = property; } public void ApplyTo(T obj, IObjectValueProvider valueProvider) { object value; if (valueProvider.TryGetValue(_property.Property.Name, out value)) { TValue? nullableValue = value as TValue?; if (!nullableValue.HasValue) nullableValue = (TValue)Convert.ChangeType(value, typeof(TValue)); _property.Set(obj, nullableValue); } } } }
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Internals.Mapping { using System; using System.ComponentModel; using Reflection; public class NullableValueObjectMapper<T, TValue> : IObjectMapper<T> where TValue : struct { readonly ReadWriteProperty<T> _property; public NullableValueObjectMapper(ReadWriteProperty<T> property) { _property = property; } public void ApplyTo(T obj, IObjectValueProvider valueProvider) { object value; if (valueProvider.TryGetValue(_property.Property.Name, out value)) { TValue? nullableValue = null; if (value != null) { var converter = TypeDescriptor.GetConverter(typeof(TValue)); nullableValue = converter.CanConvertFrom(value.GetType()) ? (TValue)converter.ConvertFrom(value) : default(TValue?); } _property.Set(obj, nullableValue); } } } }
Disable SSL for sending e-mails
using MailKit.Net.Smtp; using MimeKit; using MimeKit.Text; using System; using System.Collections.Generic; namespace SecretSanta.Utilities { public static class EmailMessage { public static void Send(MailboxAddress from, IEnumerable<MailboxAddress> to, string subject, string body) { using (var smtp = new SmtpClient()) { var message = new MimeMessage(); message.From.Add(from); message.To.AddRange(to); message.Subject = subject; message.Body = new TextPart(TextFormat.Html) { Text = body.Replace(Environment.NewLine, "<br />") }; smtp.Connect(AppSettings.SmtpHost, AppSettings.SmtpPort, true); smtp.Authenticate(AppSettings.SmtpUser, AppSettings.SmtpPass); smtp.Send(message); smtp.Disconnect(true); } } } }
using MailKit.Net.Smtp; using MimeKit; using MimeKit.Text; using System; using System.Collections.Generic; namespace SecretSanta.Utilities { public static class EmailMessage { public static void Send(MailboxAddress from, IEnumerable<MailboxAddress> to, string subject, string body) { using (var smtp = new SmtpClient()) { var message = new MimeMessage(); message.From.Add(from); message.To.AddRange(to); message.Subject = subject; message.Body = new TextPart(TextFormat.Html) { Text = body.Replace(Environment.NewLine, "<br />") }; smtp.Connect(AppSettings.SmtpHost, AppSettings.SmtpPort, false); smtp.Authenticate(AppSettings.SmtpUser, AppSettings.SmtpPass); smtp.Send(message); smtp.Disconnect(true); } } } }
Remove bad component state hack from client mover component.
using Content.Shared.GameObjects.Components.Movement; using Robust.Client.Player; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; #nullable enable namespace Content.Client.GameObjects.Components.Movement { [RegisterComponent] [ComponentReference(typeof(IMoverComponent))] public class PlayerInputMoverComponent : SharedPlayerInputMoverComponent, IMoverComponent { public override GridCoordinates LastPosition { get; set; } public override float StepSoundDistance { get; set; } public override void HandleComponentState(ComponentState? curState, ComponentState? nextState) { if (IoCManager.Resolve<IPlayerManager>().LocalPlayer!.ControlledEntity == Owner) { base.HandleComponentState(curState, nextState); } } } }
using Content.Shared.GameObjects.Components.Movement; using Robust.Shared.GameObjects; using Robust.Shared.Map; #nullable enable namespace Content.Client.GameObjects.Components.Movement { [RegisterComponent] [ComponentReference(typeof(IMoverComponent))] public class PlayerInputMoverComponent : SharedPlayerInputMoverComponent, IMoverComponent { public override GridCoordinates LastPosition { get; set; } public override float StepSoundDistance { get; set; } } }
Mark required properties in ViewModel
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Dangl.WebDocumentation.ViewModels.Admin { public class CreateProjectViewModel { [Display(Name ="Name")] public string ProjectName { get; set; } [Display(Name ="Public access")] public bool IsPublic { get; set; } [Display(Name ="Path to index")] public string PathToIndexPage { get; set; } [Display(Name ="Users with access")] public IEnumerable<string> AvailableUsers { get; set; } public IEnumerable<string> UsersWithAccess { get; set; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Dangl.WebDocumentation.ViewModels.Admin { public class CreateProjectViewModel { [Display(Name ="Name")] [Required] public string ProjectName { get; set; } [Display(Name ="Public access")] public bool IsPublic { get; set; } [Display(Name ="Path to index")] [Required] public string PathToIndexPage { get; set; } [Display(Name ="Users with access")] public IEnumerable<string> AvailableUsers { get; set; } public IEnumerable<string> UsersWithAccess { get; set; } } }
Remove set log level from base handler class.
namespace NLogging { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public abstract class Handler : IHandler { private IFormatter formatter; private LogLevel logLevel; protected Handler() { this.formatter = new Formatter(); this.logLevel = LogLevel.NOTSET; } abstract public void push(Record record); abstract public void flush(); public void SetFormatter(IFormatter formatter) { this.formatter = formatter; } public void SetLogLevel(LogLevel level) { this.logLevel = level; } } }
namespace NLogging { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public abstract class Handler : IHandler { private IFormatter formatter; protected Handler() { this.formatter = new Formatter(); } abstract public void push(Record record); abstract public void flush(); public void SetFormatter(IFormatter formatter) { this.formatter = formatter; } } }
Fix fault in temp impl of 6D handling
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; namespace Booma.Proxy { [SceneTypeCreate(GameSceneType.Pioneer2)] public sealed class Default6DCommandHandler : Command6DHandler<UnknownSubCommand6DCommand> { private int recievedCount = 0; /// <inheritdoc /> public Default6DCommandHandler(ILog logger) : base(logger) { } /// <inheritdoc /> protected override async Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, UnknownSubCommand6DCommand command) { if(Logger.IsInfoEnabled) Logger.Info($"Recieved Unknown: {command}"); //TODO: We kinda just count how many we've recieved. if(recievedCount == 4) { if(Logger.IsInfoEnabled) Logger.Info($"About to send: {nameof(BlockFinishedGameBurstingRequestPayload)}"); //If we've recieved 4 so far this is the 5th one //meaning we are done and can probably send //the UnFreeze packet to everyone. await context.PayloadSendService.SendMessage(new BlockFinishedGameBurstingRequestPayload()); } recievedCount++; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; namespace Booma.Proxy { [SceneTypeCreate(GameSceneType.Pioneer2)] public sealed class Default6DCommandHandler : Command6DHandler<UnknownSubCommand6DCommand> { private int recievedCount = 0; /// <inheritdoc /> public Default6DCommandHandler(ILog logger) : base(logger) { } /// <inheritdoc /> protected override async Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, UnknownSubCommand6DCommand command) { if(Logger.IsInfoEnabled) Logger.Info($"Recieved Unknown: {command}"); //TODO: Only 3/4 of these are static. The 0x70 is player specific and we should expect N of them where N is the player number. //TODO: We kinda just count how many we've recieved. if(recievedCount == 3) { if(Logger.IsInfoEnabled) Logger.Info($"About to send: {nameof(BlockFinishedGameBurstingRequestPayload)}"); //If we've recieved 4 so far this is the 5th one //meaning we are done and can probably send //the UnFreeze packet to everyone. await context.PayloadSendService.SendMessage(new BlockFinishedGameBurstingRequestPayload()); } recievedCount++; } } }
Add NewLine at the end of the list
 using System; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class Ol : ConverterBase { public Ol(Converter converter) : base(converter) { this.Converter.Register("ol", this); this.Converter.Register("ul", this); } public override string Convert(HtmlNode node) { return Environment.NewLine + this.TreatChildren(node); } } }
 using System; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class Ol : ConverterBase { public Ol(Converter converter) : base(converter) { this.Converter.Register("ol", this); this.Converter.Register("ul", this); } public override string Convert(HtmlNode node) { return Environment.NewLine + this.TreatChildren(node) + Environment.NewLine; } } }
Remove slug from episode ids.
namespace TraktApiSharp.Objects.Get.Shows.Episodes { using Basic; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt episode.</summary> public class TraktEpisodeIds : TraktIds { } }
namespace TraktApiSharp.Objects.Get.Shows.Episodes { using Attributes; using Newtonsoft.Json; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt episode.</summary> public class TraktEpisodeIds { /// <summary>Gets or sets the Trakt numeric id.</summary> [JsonProperty(PropertyName = "trakt")] public int Trakt { get; set; } /// <summary>Gets or sets the numeric id from thetvdb.com</summary> [JsonProperty(PropertyName = "tvdb")] public int? Tvdb { get; set; } /// <summary>Gets or sets the id from imdb.com<para>Nullable</para></summary> [JsonProperty(PropertyName = "imdb")] [Nullable] public string Imdb { get; set; } /// <summary>Gets or sets the numeric id from themoviedb.org</summary> [JsonProperty(PropertyName = "tmdb")] public int? Tmdb { get; set; } /// <summary>Gets or sets the numeric id from tvrage.com</summary> [JsonProperty(PropertyName = "tvrage")] public int? TvRage { get; set; } /// <summary>Returns, whether any id has been set.</summary> [JsonIgnore] public bool HasAnyId => Trakt > 0 || Tvdb > 0 || !string.IsNullOrEmpty(Imdb) || Tmdb > 0 || TvRage > 0; /// <summary>Gets the most reliable id from those that have been set.</summary> /// <returns>The id as a string or an empty string, if no id is set.</returns> public string GetBestId() { if (Trakt > 0) return Trakt.ToString(); if (Tvdb.HasValue && Tvdb.Value > 0) return Tvdb.Value.ToString(); if (!string.IsNullOrEmpty(Imdb)) return Imdb; if (Tmdb.HasValue && Tmdb.Value > 0) return Tmdb.Value.ToString(); if (TvRage.HasValue && TvRage.Value > 0) return TvRage.Value.ToString(); return string.Empty; } } }
Test demonstrating an edge case of generic interfaces
using NUnit.Framework; namespace NSubstitute.Acceptance.Specs { [TestFixture] public class MatchingDerivedTypesForGenerics { IGenMethod _sub; [SetUp] public void Setup() { _sub = Substitute.For<IGenMethod>(); } [Test] public void Calls_to_generic_types_with_derived_parameters_should_be_matched () { _sub.Call(new GMParam1()); _sub.Call(new GMParam2()); _sub.Received(2).Call(Arg.Any<IGMParam>()); } public interface IGenMethod { void Call<T>(T param) where T : IGMParam; } public interface IGMParam { } public class GMParam1 : IGMParam { } public class GMParam2 : IGMParam { } } }
using NUnit.Framework; namespace NSubstitute.Acceptance.Specs { [TestFixture] public class MatchingDerivedTypesForGenerics { IGenMethod _sub; [SetUp] public void Setup() { _sub = Substitute.For<IGenMethod>(); } [Test] public void Calls_to_generic_types_with_derived_parameters_should_be_matched () { _sub.Call(new GMParam1()); _sub.Call(new GMParam2()); _sub.Received(2).Call(Arg.Any<IGMParam>()); } public interface IGenMethod { void Call<T>(T param) where T : IGMParam; } public interface IGMParam { } public class GMParam1 : IGMParam { } public class GMParam2 : IGMParam { } } [TestFixture] public class Calls_to_members_on_generic_interface { [Test] public void Calls_to_members_on_generic_interfaces_match_based_on_type_compatibility() { var sub = Substitute.For<IGenInterface<IGMParam>>(); sub.Call(new GMParam1()); sub.Call(new GMParam2()); sub.Call(new GMParam3()); sub.Received(2).Call(Arg.Any<IGMParam>()); sub.Received(1).Call(Arg.Any<GMParam3>()); } public interface IGenInterface<T> { void Call(T param); void Call(GMParam3 param); } public interface IGMParam { } public class GMParam1 : IGMParam { } public class GMParam2 : IGMParam { } public class GMParam3 { } } }