Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix issue where ratio was always returning "1"
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return Width / Height; } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height); } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
Allow empty semver components to be deserialised as this might be an archived component
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace OctopusPuppet.DeploymentPlanner { public class SemVerJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = JToken.Load(reader); var version = token.ToString(); return new SemVer(version); } public override bool CanConvert(Type objectType) { return typeof(SemVer).IsAssignableFrom(objectType); } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace OctopusPuppet.DeploymentPlanner { public class SemVerJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = JToken.Load(reader); var version = token.ToString(); if (string.IsNullOrEmpty(version)) return null; return new SemVer(version); } public override bool CanConvert(Type objectType) { return typeof(SemVer).IsAssignableFrom(objectType); } } }
Fix filename not being populated
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Octokit { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PullRequestFile { public PullRequestFile() { } public PullRequestFile(string sha, string fileName, string status, int additions, int deletions, int changes, Uri blobUri, Uri rawUri, Uri contentsUri, string patch) { Sha = sha; FileName = fileName; Status = status; Additions = additions; Deletions = deletions; Changes = changes; BlobUri = blobUri; RawUri = rawUri; ContentsUri = contentsUri; Patch = patch; } public string Sha { get; protected set; } public string FileName { get; protected set; } public string Status { get; protected set; } public int Additions { get; protected set; } public int Deletions { get; protected set; } public int Changes { get; protected set; } public Uri BlobUri { get; protected set; } public Uri RawUri { get; protected set; } public Uri ContentsUri { get; protected set; } public string Patch { get; protected set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Sha: {0} Filename: {1} Additions: {2} Deletions: {3} Changes: {4}", Sha, FileName, Additions, Deletions, Changes); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Octokit.Internal; namespace Octokit { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PullRequestFile { public PullRequestFile() { } public PullRequestFile(string sha, string fileName, string status, int additions, int deletions, int changes, Uri blobUri, Uri rawUri, Uri contentsUri, string patch) { Sha = sha; FileName = fileName; Status = status; Additions = additions; Deletions = deletions; Changes = changes; BlobUri = blobUri; RawUri = rawUri; ContentsUri = contentsUri; Patch = patch; } public string Sha { get; protected set; } [Parameter(Key = "filename")] public string FileName { get; protected set; } public string Status { get; protected set; } public int Additions { get; protected set; } public int Deletions { get; protected set; } public int Changes { get; protected set; } public Uri BlobUri { get; protected set; } public Uri RawUri { get; protected set; } public Uri ContentsUri { get; protected set; } public string Patch { get; protected set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Sha: {0} FileName: {1} Additions: {2} Deletions: {3} Changes: {4}", Sha, FileName, Additions, Deletions, Changes); } } } }
Fix a ref to FinnAngelo.PomoFish
using Common.Logging; using FinnAngelo.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Diagnostics; namespace FinnAngelo.PomoFishTests { [TestClass] public class IconTests { [TestMethod] //[Ignore] public void GivenDestroyMethod_WhenGet10000Icons_ThenNoException() { //Given var moqLog = new Mock<ILog>(); var im = new IconManager(moqLog.Object); //When for (int a = 0; a < 150; a++) { im.SetNotifyIcon(null, Pomodoro.Resting, a); } //Then Assert.IsTrue(true, "this too, shall pass..."); } } }
using Common.Logging; using FinnAngelo.PomoFish; using FinnAngelo.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Diagnostics; namespace FinnAngelo.PomoFishTests { [TestClass] public class IconTests { [TestMethod] //[Ignore] public void GivenDestroyMethod_WhenGet10000Icons_ThenNoException() { //Given var moqLog = new Mock<ILog>(); var im = new IconManager(moqLog.Object); //When for (int a = 0; a < 150; a++) { im.SetNotifyIcon(null, Pomodoro.Resting, a); } //Then Assert.IsTrue(true, "this too, shall pass..."); } } }
Change Check tests to restore default behaviour
using System; using EdlinSoftware.Verifier.Tests.Support; using Xunit; namespace EdlinSoftware.Verifier.Tests { public class CheckTests : IDisposable { private readonly StringVerifier _verifier; private static readonly Action<string> DefaultAssertionFailed = Verifier.AssertionFailed; public CheckTests() { _verifier = new StringVerifier() .AddVerifiers(sut => VerificationResult.Critical(sut == "success" ? null : "error")); } [Fact] public void Check_Failure_ByDefault() { Assert.Throws<VerificationException>(() => _verifier.Check("failure")); } [Fact] public void Check_Success_ByDefault() { _verifier.Check("success"); } [Fact] public void Check_CustomAssert() { Verifier.AssertionFailed = errorMessage => throw new InvalidOperationException(errorMessage); Assert.Equal( "error", Assert.Throws<InvalidOperationException>(() => _verifier.Check("failure")).Message ); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { Verifier.AssertionFailed = DefaultAssertionFailed; } } }
using System; using EdlinSoftware.Verifier.Tests.Support; using Xunit; namespace EdlinSoftware.Verifier.Tests { public class CheckTests : IDisposable { private readonly StringVerifier _verifier; private static readonly Action<string> DefaultAssertionFailed = Verifier.AssertionFailed; public CheckTests() { Verifier.AssertionFailed = DefaultAssertionFailed; _verifier = new StringVerifier() .AddVerifiers(sut => VerificationResult.Critical(sut == "success" ? null : "error")); } [Fact] public void Check_Failure_ByDefault() { Assert.Throws<VerificationException>(() => _verifier.Check("failure")); } [Fact] public void Check_Success_ByDefault() { _verifier.Check("success"); } [Fact] public void Check_CustomAssert() { Verifier.AssertionFailed = errorMessage => throw new InvalidOperationException(errorMessage); Assert.Equal( "error", Assert.Throws<InvalidOperationException>(() => _verifier.Check("failure")).Message ); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { Verifier.AssertionFailed = DefaultAssertionFailed; } } }
Implement property converter for XPath
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Models.PublishedContent; using Zbu.Blocks.PropertyEditors; namespace Zbu.Blocks.DataType { // note: can cache the converted value at .Content level because it's just // a deserialized json and it does not reference anything outside its content. [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] [PropertyValueType(typeof(IEnumerable<StructureDataValue>))] public class StructuresConverter : IPropertyValueConverter { public object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { var json = source.ToString(); if (string.IsNullOrWhiteSpace(json)) return null; var value = JsonSerializer.Instance.Deserialize<StructureDataValue[]>(json); foreach (var v in value) v.EnsureFragments(preview); return value; } public object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview) { return source; } public object ConvertSourceToXPath(PublishedPropertyType propertyType, object source, bool preview) { throw new NotImplementedException(); } public bool IsConverter(PublishedPropertyType propertyType) { #if UMBRACO_6 return propertyType.PropertyEditorGuid == StructuresDataType.DataTypeGuid; #else return propertyType.PropertyEditorAlias == StructuresPropertyEditor.StructuresAlias; #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Models.PublishedContent; using Zbu.Blocks.PropertyEditors; namespace Zbu.Blocks.DataType { // note: can cache the converted value at .Content level because it's just // a deserialized json and it does not reference anything outside its content. [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] [PropertyValueType(typeof(IEnumerable<StructureDataValue>))] public class StructuresConverter : IPropertyValueConverter { public object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { // data == source so we can return json to xpath return source; } public object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview) { // object == deserialized source var json = source.ToString(); if (string.IsNullOrWhiteSpace(json)) return null; var value = JsonSerializer.Instance.Deserialize<StructureDataValue[]>(json); foreach (var v in value) v.EnsureFragments(preview); return value; } public object ConvertSourceToXPath(PublishedPropertyType propertyType, object source, bool preview) { // we don't really want to support XML for blocks // so xpath == source == data == the original json return source; } public bool IsConverter(PublishedPropertyType propertyType) { #if UMBRACO_6 return propertyType.PropertyEditorGuid == StructuresDataType.DataTypeGuid; #else return propertyType.PropertyEditorAlias == StructuresPropertyEditor.StructuresAlias; #endif } } }
Fix error when substituting arguments
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Parsel { internal static class ReplaceParameter { public static Expression Apply<S, T>(this Expression<Func<S, T>> f, Expression s) { return f.Body.Replace(f.Parameters[0], s); } public static Expression Apply<S, T, V>(this Expression<Func<S, T, V>> f, Expression s, Expression t) { return f.Body.Replace(f.Parameters[0], s).Replace(f.Parameters[1], s); } public static Expression Replace(this Expression body, ParameterExpression parameter, Expression replacement) { return new ReplaceParameterVisitor(parameter, replacement).Visit(body); } } internal class ReplaceParameterVisitor : ExpressionVisitor { private readonly ParameterExpression parameter; private readonly Expression replacement; public ReplaceParameterVisitor(ParameterExpression parameter, Expression replacement) { this.parameter = parameter; this.replacement = replacement; } protected override Expression VisitParameter(ParameterExpression node) { if (node.Equals(parameter)) { return replacement; } else { return base.VisitParameter(node); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Parsel { internal static class ReplaceParameter { public static Expression Apply<S, T>(this Expression<Func<S, T>> f, Expression s) { return f.Body.Replace(f.Parameters[0], s); } public static Expression Apply<S, T, V>(this Expression<Func<S, T, V>> f, Expression s, Expression t) { return f.Body.Replace(f.Parameters[0], s).Replace(f.Parameters[1], t); } public static Expression Replace(this Expression body, ParameterExpression parameter, Expression replacement) { return new ReplaceParameterVisitor(parameter, replacement).Visit(body); } } internal class ReplaceParameterVisitor : ExpressionVisitor { private readonly ParameterExpression parameter; private readonly Expression replacement; public ReplaceParameterVisitor(ParameterExpression parameter, Expression replacement) { this.parameter = parameter; this.replacement = replacement; } protected override Expression VisitParameter(ParameterExpression node) { if (node.Equals(parameter)) { return replacement; } else { return base.VisitParameter(node); } } } }
Update location of env vars
using System; using NUnit.Framework; using Centroid; namespace Schedules.API.Tests { [TestFixture, Category("System")] public class SystemTests { [Test] public void CheckThatEnvironmentVariablesExist() { dynamic config = Config.FromFile("config.json"); foreach (var variable in config.variables) { var value = Environment.GetEnvironmentVariable(variable); Assert.That(!String.IsNullOrEmpty(value), String.Format("{0} does not have a value.", variable)); } } } }
using System; using NUnit.Framework; using Centroid; namespace Schedules.API.Tests { [TestFixture, Category("System")] public class SystemTests { [Test] public void CheckThatEnvironmentVariablesExist() { dynamic config = Config.FromFile("config.json"); foreach (var variable in config.all.variables) { var value = Environment.GetEnvironmentVariable(variable); Assert.That(!String.IsNullOrEmpty(value), String.Format("{0} does not have a value.", variable)); } } } }
Update use agent for v2
namespace MultiMiner.Win { public static class UserAgent { public const string AgentString = "MultiMiner/V1"; } }
namespace MultiMiner.Win { public static class UserAgent { public const string AgentString = "MultiMiner/V2"; } }
Remove unneeded reference to PrismApplication base class.
using System.Windows; using Prism.DryIoc; using Prism.Ioc; using SimpSim.NET.WPF.ViewModels; using SimpSim.NET.WPF.Views; namespace SimpSim.NET.WPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : PrismApplication { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton<SimpleSimulator>(); containerRegistry.Register<IUserInputService, UserInputService>(); containerRegistry.Register<IDialogServiceAdapter, DialogServiceAdapter>(); containerRegistry.RegisterSingleton<StateSaver>(); containerRegistry.RegisterDialog<AssemblyEditorDialog, AssemblyEditorDialogViewModel>(); } } }
using System.Windows; using Prism.Ioc; using SimpSim.NET.WPF.ViewModels; using SimpSim.NET.WPF.Views; namespace SimpSim.NET.WPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton<SimpleSimulator>(); containerRegistry.Register<IUserInputService, UserInputService>(); containerRegistry.Register<IDialogServiceAdapter, DialogServiceAdapter>(); containerRegistry.RegisterSingleton<StateSaver>(); containerRegistry.RegisterDialog<AssemblyEditorDialog, AssemblyEditorDialogViewModel>(); } } }
Change TODO comments to reference current issue on Sockets perf counters.
// 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; namespace System.Net { internal enum SocketPerfCounterName { SocketConnectionsEstablished = 0, // these enum values are used as index SocketBytesReceived, SocketBytesSent, SocketDatagramsReceived, SocketDatagramsSent, } internal sealed class SocketPerfCounter { private static SocketPerfCounter s_instance; private static object s_lockObject = new object(); public static SocketPerfCounter Instance { get { if (Volatile.Read(ref s_instance) == null) { lock (s_lockObject) { if (Volatile.Read(ref s_instance) == null) { s_instance = new SocketPerfCounter(); } } } return s_instance; } } public bool Enabled { get { // TODO (Event logging for System.Net.* #2500): Implement socket perf counters. return false; } } public void Increment(SocketPerfCounterName perfCounter) { // TODO (Event logging for System.Net.* #2500): Implement socket perf counters. } public void Increment(SocketPerfCounterName perfCounter, long amount) { // TODO (Event logging for System.Net.* #2500): Implement socket perf counters. } } }
// 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; namespace System.Net { internal enum SocketPerfCounterName { SocketConnectionsEstablished = 0, // these enum values are used as index SocketBytesReceived, SocketBytesSent, SocketDatagramsReceived, SocketDatagramsSent, } internal sealed class SocketPerfCounter { private static SocketPerfCounter s_instance; private static object s_lockObject = new object(); public static SocketPerfCounter Instance { get { if (Volatile.Read(ref s_instance) == null) { lock (s_lockObject) { if (Volatile.Read(ref s_instance) == null) { s_instance = new SocketPerfCounter(); } } } return s_instance; } } public bool Enabled { get { // TODO (#7833): Implement socket perf counters. return false; } } public void Increment(SocketPerfCounterName perfCounter) { // TODO (#7833): Implement socket perf counters. } public void Increment(SocketPerfCounterName perfCounter, long amount) { // TODO (#7833): Implement socket perf counters. } } }
Use && instead of & to perform AND operation
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oberon0.Compiler.Expressions.Operations { using JetBrains.Annotations; using Oberon0.Compiler.Definitions; using Oberon0.Compiler.Expressions.Constant; using Oberon0.Compiler.Expressions.Operations.Internal; using Oberon0.Compiler.Types; [ArithmeticOperation(OberonGrammarLexer.OR, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)] [ArithmeticOperation(OberonGrammarLexer.AND, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)] [UsedImplicitly] internal class OpRelOp2 : BinaryOperation { protected override Expression BinaryOperate(BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters) { if (bin.LeftHandSide.IsConst && bin.RightHandSide.IsConst) { var left = (ConstantExpression)bin.LeftHandSide; var right = (ConstantExpression)bin.RightHandSide; bool res = false; switch (operationParameters.Operation) { case OberonGrammarLexer.AND: res = left.ToBool() & right.ToBool(); break; case OberonGrammarLexer.OR: res = left.ToBool() || right.ToBool(); break; } return new ConstantBoolExpression(res); } return bin; // expression remains the same } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oberon0.Compiler.Expressions.Operations { using JetBrains.Annotations; using Oberon0.Compiler.Definitions; using Oberon0.Compiler.Expressions.Constant; using Oberon0.Compiler.Expressions.Operations.Internal; using Oberon0.Compiler.Types; [ArithmeticOperation(OberonGrammarLexer.OR, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)] [ArithmeticOperation(OberonGrammarLexer.AND, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)] [UsedImplicitly] internal class OpRelOp2 : BinaryOperation { protected override Expression BinaryOperate(BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters) { if (bin.LeftHandSide.IsConst && bin.RightHandSide.IsConst) { var left = (ConstantExpression)bin.LeftHandSide; var right = (ConstantExpression)bin.RightHandSide; bool res = false; switch (operationParameters.Operation) { case OberonGrammarLexer.AND: res = left.ToBool() && right.ToBool(); break; case OberonGrammarLexer.OR: res = left.ToBool() || right.ToBool(); break; } return new ConstantBoolExpression(res); } return bin; // expression remains the same } } }
Copy list before iterating to prevent modifications during iteration
using System; using System.Collections; using System.Collections.Generic; namespace NHotkey.Wpf { class WeakReferenceCollection<T> : IEnumerable<T> where T : class { private readonly List<WeakReference> _references = new List<WeakReference>(); public IEnumerator<T> GetEnumerator() { foreach (var reference in _references) { var target = reference.Target; if (target != null) yield return (T) target; } Trim(); } public void Add(T item) { _references.Add(new WeakReference(item)); } public void Remove(T item) { _references.RemoveAll(r => (r.Target ?? item) == item); } public void Trim() { _references.RemoveAll(r => !r.IsAlive); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace NHotkey.Wpf { class WeakReferenceCollection<T> : IEnumerable<T> where T : class { private readonly List<WeakReference> _references = new List<WeakReference>(); public IEnumerator<T> GetEnumerator() { var references = _references.ToList(); foreach (var reference in references) { var target = reference.Target; if (target != null) yield return (T) target; } Trim(); } public void Add(T item) { _references.Add(new WeakReference(item)); } public void Remove(T item) { _references.RemoveAll(r => (r.Target ?? item) == item); } public void Trim() { _references.RemoveAll(r => !r.IsAlive); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
Update comment about this Interface usage - maybe we can remove this later on
namespace Umbraco.Web.UI { /// <summary> /// This is used for anything that is assigned to an app /// </summary> /// <remarks> /// Currently things that need to be assigned to an app in order for user security to work are: /// dialogs, ITasks, editors /// </remarks> public interface IAssignedApp { /// <summary> /// Returns the app alias that this element belongs to /// </summary> string AssignedApp { get; } } }
namespace Umbraco.Web.UI { /// <summary> /// This is used for anything that is assigned to an app /// </summary> /// <remarks> /// Currently things that need to be assigned to an app in order for user security to work are: /// LegacyDialogTask /// </remarks> public interface IAssignedApp { /// <summary> /// Returns the app alias that this element belongs to /// </summary> string AssignedApp { get; } } }
Fix issue where test writer was writing when nothing was listening.
using System; using System.IO; using System.Text; using Xunit.Abstractions; namespace Foundatio.Tests.Utility { public class TestOutputWriter : TextWriter { private readonly ITestOutputHelper _output; public TestOutputWriter(ITestOutputHelper output) { _output = output; } public override Encoding Encoding { get { return Encoding.UTF8; } } public override void WriteLine(string value) { _output.WriteLine(value); } public override void WriteLine() { _output.WriteLine(String.Empty); } } }
using System; using System.Diagnostics; using System.IO; using System.Text; using Xunit.Abstractions; namespace Foundatio.Tests.Utility { public class TestOutputWriter : TextWriter { private readonly ITestOutputHelper _output; public TestOutputWriter(ITestOutputHelper output) { _output = output; } public override Encoding Encoding { get { return Encoding.UTF8; } } public override void WriteLine(string value) { try { _output.WriteLine(value); } catch (Exception ex) { Trace.WriteLine(ex); } } public override void WriteLine() { WriteLine(String.Empty); } } }
Move Shipeditor tests to the Voxelgon.Shipeditor.Tests namespace
using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using Voxelgon.ShipEditor; namespace Voxelgon.Tests { public class WallTests { [Test] public void WallCannotHaveDuplicateVertices() { //Arrange var editor = new ShipEditor.ShipEditor(); var wall = new Wall(editor); var nodes = new List<Vector3>(); nodes.Add(new Vector3(5, 8, 3)); //Act wall.UpdateVertices(nodes, ShipEditor.ShipEditor.BuildMode.Polygon); //Assert Assert.That(wall.ValidVertex(new Vector3(5, 8, 3)), Is.False); } } }
using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using Voxelgon.ShipEditor; namespace Voxelgon.ShipEditor.Tests { public class WallTests { [Test] public void WallCannotHaveDuplicateVertices() { //Arrange var editor = new ShipEditor(); var wall = new Wall(editor); var nodes = new List<Vector3>(); nodes.Add(new Vector3(5, 8, 3)); //Act wall.UpdateVertices(nodes, ShipEditor.BuildMode.Polygon); //Assert Assert.That(wall.ValidVertex(new Vector3(5, 8, 3)), Is.False); } } }
Add LogLevel option to restclient config
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NTwitch.Rest { public class TwitchRestClientConfig { public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NTwitch.Rest { public class TwitchRestClientConfig { public string BaseUrl { get; set; } = "https://api.twitch.tv/kraken/"; public LogLevel LogLevel { get; set; } = LogLevel.Errors; } }
Add test coverage for per-ruleset setup screens
// 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.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Osu.Beatmaps; using osu.Game.Screens.Edit; using osu.Game.Screens.Edit.Setup; namespace osu.Game.Tests.Visual.Editing { [TestFixture] public class TestSceneSetupScreen : EditorClockTestScene { [Cached(typeof(EditorBeatmap))] [Cached(typeof(IBeatSnapProvider))] private readonly EditorBeatmap editorBeatmap; public TestSceneSetupScreen() { editorBeatmap = new EditorBeatmap(new OsuBeatmap()); } [BackgroundDependencyLoader] private void load() { Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap); Child = new SetupScreen { State = { Value = Visibility.Visible }, }; } } }
// 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.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets; using osu.Game.Rulesets.Catch; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Beatmaps; using osu.Game.Rulesets.Taiko; using osu.Game.Screens.Edit; using osu.Game.Screens.Edit.Setup; namespace osu.Game.Tests.Visual.Editing { [TestFixture] public class TestSceneSetupScreen : EditorClockTestScene { [Cached(typeof(EditorBeatmap))] [Cached(typeof(IBeatSnapProvider))] private readonly EditorBeatmap editorBeatmap; public TestSceneSetupScreen() { editorBeatmap = new EditorBeatmap(new OsuBeatmap()); } [Test] public void TestOsu() => runForRuleset(new OsuRuleset().RulesetInfo); [Test] public void TestTaiko() => runForRuleset(new TaikoRuleset().RulesetInfo); [Test] public void TestCatch() => runForRuleset(new CatchRuleset().RulesetInfo); [Test] public void TestMania() => runForRuleset(new ManiaRuleset().RulesetInfo); private void runForRuleset(RulesetInfo rulesetInfo) { AddStep("create screen", () => { editorBeatmap.BeatmapInfo.Ruleset = rulesetInfo; Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap); Child = new SetupScreen { State = { Value = Visibility.Visible }, }; }); } } }
Add missing function to interface
namespace TheCollection.Business { using System.Collections.Generic; using System.Threading.Tasks; public interface ISearchRepository<T> where T : class { Task<IEnumerable<T>> SearchAsync(string searchterm, int top = 0); } }
namespace TheCollection.Business { using System.Collections.Generic; using System.Threading.Tasks; public interface ISearchRepository<T> where T : class { Task<IEnumerable<T>> SearchAsync(string searchterm, int top = 0); Task<long> SearchRowCountAsync(string searchterm); } }
Prepend debug messages in the web chat example.
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <input type="text" id="msg" /> <a id="broadcast" href="#">Send message</a> <p>Messages : </p> <ul id="messages"> </ul> <script type="text/javascript"> $(function () { // Proxy created on the fly var chat = $.connection.chat; $.connection.hub.logging = true; // Declare a function on the chat hub so the server can invoke it chat.client.addMessage = function (message, from) { $('#messages').append('<li>' + message + " from " + from + '</li>'); }; chat.client.onConsoleMessage = function (message) { $('#messages').append('<li> From the console application : ' + message + '</li>'); }; $("#broadcast").click(function () { // Call the chat method on the server chat.server.send($('#msg').val()) .done(function () { console.log('Success!'); }) .fail(function (e) { console.warn(e); }); }); $("#broadcast").hide(); // Start the connection $.connection.hub.start({transport: 'auto'},function () { $("#broadcast").show(); console.log("Success"); }); }); </script>
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <input type="text" id="msg" /> <a id="broadcast" href="#">Send message</a> <p>Messages : </p> <ul id="messages"> </ul> <script type="text/javascript"> $(function () { // Proxy created on the fly var chat = $.connection.chat; $.connection.hub.logging = true; // Declare a function on the chat hub so the server can invoke it chat.client.addMessage = function (message, from) { $('#messages').prepend('<li>' + message + " from " + from + '</li>'); }; chat.client.onConsoleMessage = function (message) { $('#messages').prepend('<li> From the console application : ' + message + '</li>'); }; $("#broadcast").click(function () { // Call the chat method on the server chat.server.send($('#msg').val()) .done(function () { console.log('Success!'); }) .fail(function (e) { console.warn(e); }); }); $("#broadcast").hide(); // Start the connection $.connection.hub.start({transport: 'auto'},function () { $("#broadcast").show(); console.log("Success"); }); }); </script>
Check if appharbour will trigger a build
@{ ViewBag.Title = "GAMES"; } <h2>GAMES:</h2> <p>list all games here</p>
@{ ViewBag.Title = "GAMES"; } <h2>GAMES:</h2> <p>list all games here!!!</p>
Test file output using char name and total level.
using System; using FG5eXmlToPDF; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FG5eXmlToPdf.Tests { [TestClass] public class UnitTest1 { [TestMethod] public void ReadWriteTest() { var currentDirectory = System.IO.Directory.GetCurrentDirectory(); var character = FG5eXml.LoadCharacter($@"{currentDirectory}\rita.xml"); FG5ePdf.Write( character, $@"{currentDirectory}\out.pdf"); } } }
using System; using System.Linq; using FG5eXmlToPDF; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FG5eXmlToPdf.Tests { [TestClass] public class UnitTest1 { [TestMethod] public void ReadWriteTest() { var currentDirectory = System.IO.Directory.GetCurrentDirectory(); var character = FG5eXml.LoadCharacter($@"{currentDirectory}\rita.xml"); var charName = character.Properities.FirstOrDefault((x) => x.Name == "Name")?.Value; var level = character.Properities.FirstOrDefault((x) => x.Name == "LevelTotal")?.Value; FG5ePdf.Write( character, $@"{currentDirectory}\{charName} ({level}).pdf"); } } }
Add text for debug purposes to see if the job has been running
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TvShowReminderWorker { class Program { static void Main(string[] args) { } } }
using System; namespace TvShowReminderWorker { class Program { static void Main(string[] args) { Console.WriteLine("I am the web job, I ran at {0}", DateTime.Now); } } }
Reset page number to 1 when perform a new search. Work items: 569
using System; using System.Linq; using Microsoft.VisualStudio.ExtensionsExplorer; namespace NuGet.Dialog.Providers { internal class PackagesSearchNode : PackagesTreeNodeBase { private string _searchText; private readonly PackagesTreeNodeBase _baseNode; public PackagesTreeNodeBase BaseNode { get { return _baseNode; } } public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) : base(parent, provider) { if (baseNode == null) { throw new ArgumentNullException("baseNode"); } _searchText = searchText; _baseNode = baseNode; // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer IsSearchResultsNode = true; } public override string Name { get { return Resources.Dialog_RootNodeSearch; } } public void SetSearchText(string newSearchText) { if (newSearchText == null) { throw new ArgumentNullException("newSearchText"); } if (_searchText != newSearchText) { _searchText = newSearchText; if (IsSelected) { ResetQuery(); Refresh(); } } } public override IQueryable<IPackage> GetPackages() { return _baseNode.GetPackages().Find(_searchText); } } }
using System; using System.Linq; using Microsoft.VisualStudio.ExtensionsExplorer; namespace NuGet.Dialog.Providers { internal class PackagesSearchNode : PackagesTreeNodeBase { private string _searchText; private readonly PackagesTreeNodeBase _baseNode; public PackagesTreeNodeBase BaseNode { get { return _baseNode; } } public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) : base(parent, provider) { if (baseNode == null) { throw new ArgumentNullException("baseNode"); } _searchText = searchText; _baseNode = baseNode; // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer IsSearchResultsNode = true; } public override string Name { get { return Resources.Dialog_RootNodeSearch; } } public void SetSearchText(string newSearchText) { if (newSearchText == null) { throw new ArgumentNullException("newSearchText"); } if (_searchText != newSearchText) { _searchText = newSearchText; if (IsSelected) { ResetQuery(); LoadPage(1); } } } public override IQueryable<IPackage> GetPackages() { return _baseNode.GetPackages().Find(_searchText); } } }
Add additional comparison methods for string establisher
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Establishment { public class StringEstablisher : BaseClassEstablisher<string> { public bool IsNullOrEmpty(string value) { if (!string.IsNullOrEmpty(value)) { return HandleFailure(new ArgumentException("string value must be null or empty")); } return true; } public bool IsNotNullOrEmpty(string value) { if (string.IsNullOrEmpty(value)) { return HandleFailure(new ArgumentException("string value must not be null or empty")); } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Establishment { public class StringEstablisher : BaseClassEstablisher<string> { public bool IsNullOrEmpty(string value) { if (!string.IsNullOrEmpty(value)) { return HandleFailure(new ArgumentException("string value must be null or empty")); } return true; } public bool IsNotNullOrEmpty(string value) { if (string.IsNullOrEmpty(value)) { return HandleFailure(new ArgumentException("string value must not be null or empty")); } return true; } public bool IsEmpty(string value) { if (value != string.Empty) { return HandleFailure(new ArgumentException("string value must be empty")); } return true; } public bool IsNotEmpty(string value) { if (value == string.Empty) { return HandleFailure(new ArgumentException("string value must not be empty")); } return true; } } }
Make catch provide some HP at DrainRate=10
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Catch.Scoring { public class CatchScoreProcessor : ScoreProcessor<CatchHitObject> { public CatchScoreProcessor(DrawableRuleset<CatchHitObject> drawableRuleset) : base(drawableRuleset) { } private float hpDrainRate; protected override void ApplyBeatmap(Beatmap<CatchHitObject> beatmap) { base.ApplyBeatmap(beatmap); hpDrainRate = beatmap.BeatmapInfo.BaseDifficulty.DrainRate; } protected override double HpFactorFor(Judgement judgement, HitResult result) { switch (result) { case HitResult.Miss when judgement.IsBonus: return 0; case HitResult.Miss: return hpDrainRate; default: return 10 - hpDrainRate; // Award less HP as drain rate is increased } } public override HitWindows CreateHitWindows() => new CatchHitWindows(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Catch.Scoring { public class CatchScoreProcessor : ScoreProcessor<CatchHitObject> { public CatchScoreProcessor(DrawableRuleset<CatchHitObject> drawableRuleset) : base(drawableRuleset) { } private float hpDrainRate; protected override void ApplyBeatmap(Beatmap<CatchHitObject> beatmap) { base.ApplyBeatmap(beatmap); hpDrainRate = beatmap.BeatmapInfo.BaseDifficulty.DrainRate; } protected override double HpFactorFor(Judgement judgement, HitResult result) { switch (result) { case HitResult.Miss when judgement.IsBonus: return 0; case HitResult.Miss: return hpDrainRate; default: return 10.2 - hpDrainRate; // Award less HP as drain rate is increased } } public override HitWindows CreateHitWindows() => new CatchHitWindows(); } }
Fix default log level filter
using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; namespace Gelf.Extensions.Logging { public class GelfLoggerOptions { public GelfLoggerOptions() { Filter = (name, level) => level > LogLevel; } /// <summary> /// GELF server host. /// </summary> public string Host { get; set; } /// <summary> /// GELF server port. /// </summary> public int Port { get; set; } = 12201; /// <summary> /// Log source name mapped to the GELF host field. /// </summary> public string LogSource { get; set; } /// <summary> /// Enable GZip message compression. /// </summary> public bool Compress { get; set; } = true; /// <summary> /// The message size in bytes under which messages will not be compressed. /// </summary> public int CompressionThreshold { get; set; } = 512; /// <summary> /// Function used to filter log events based on logger name and level. Uses <see cref="LogLevel"/> by default. /// </summary> public Func<string, LogLevel, bool> Filter { get; set; } /// <summary> /// The defualt log level. /// </summary> public LogLevel LogLevel { get; set; } = LogLevel.Information; /// <summary> /// Additional fields that will be attached to all log messages. /// </summary> public Dictionary<string, string> AdditionalFields { get; } = new Dictionary<string, string>(); } }
using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; namespace Gelf.Extensions.Logging { public class GelfLoggerOptions { public GelfLoggerOptions() { Filter = (name, level) => level >= LogLevel; } /// <summary> /// GELF server host. /// </summary> public string Host { get; set; } /// <summary> /// GELF server port. /// </summary> public int Port { get; set; } = 12201; /// <summary> /// Log source name mapped to the GELF host field. /// </summary> public string LogSource { get; set; } /// <summary> /// Enable GZip message compression. /// </summary> public bool Compress { get; set; } = true; /// <summary> /// The message size in bytes under which messages will not be compressed. /// </summary> public int CompressionThreshold { get; set; } = 512; /// <summary> /// Function used to filter log events based on logger name and level. Uses <see cref="LogLevel"/> by default. /// </summary> public Func<string, LogLevel, bool> Filter { get; set; } /// <summary> /// The defualt log level. /// </summary> public LogLevel LogLevel { get; set; } = LogLevel.Information; /// <summary> /// Additional fields that will be attached to all log messages. /// </summary> public Dictionary<string, string> AdditionalFields { get; } = new Dictionary<string, string>(); } }
Add object's IsNull & IsNotNull extentions
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataGenExtensions { public static class ObjectExtensions { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataGenExtensions { public static class ObjectExtensions { public static bool IsNull(this object objectInstance) { return objectInstance == null; } public static bool IsNotNull(this object objectInstance) { return !objectInstance.IsNull(); } } }
Remove limit check on data extraction queries
using Slicer.Utils.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Slicer.Utils.Validators { // Validates data extraction queries public class DataExtractionQueryValidator { Dictionary<string, dynamic> Query; public DataExtractionQueryValidator(Dictionary<string, dynamic> query) { this.Query = query; } // Validate data extraction query, if the query is valid will return true public bool Validator() { if (this.Query.ContainsKey("limit")) { var limitValue = (int) this.Query["limit"]; if (limitValue > 100) { throw new InvalidQueryException("The field 'limit' has a value max of 100."); } } if (this.Query.ContainsKey("fields")) { var fields = this.Query["fields"]; if (fields.Count > 10) { throw new InvalidQueryException("The key 'fields' in data extraction result must have up to 10 fields."); } } return true; } } }
using Slicer.Utils.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Slicer.Utils.Validators { // Validates data extraction queries public class DataExtractionQueryValidator { Dictionary<string, dynamic> Query; public DataExtractionQueryValidator(Dictionary<string, dynamic> query) { this.Query = query; } // Validate data extraction query, if the query is valid will return true public bool Validator() { if (this.Query.ContainsKey("fields")) { var fields = this.Query["fields"]; if (fields.Count > 10) { throw new InvalidQueryException("The key 'fields' in data extraction result must have up to 10 fields."); } } return true; } } }
Use types instead of fully qualified names.
namespace Tabster.Core.Plugins { public interface ITabsterPlugin { string Name { get; } string Description { get; } string Author { get; } string Version { get; } string[] PluginClasses { get; } } }
using System; namespace Tabster.Core.Plugins { public interface ITabsterPlugin { string Name { get; } string Description { get; } string Author { get; } string Version { get; } Type[] Types { get; } } }
Add possibility to register events on App, like we do on HTML DOM
using UnityEngine; public class Application : MonoBehaviour { public ModelContainer Model; public ControllerContainer Controller; public ViewContainer View; }
using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Application : MonoBehaviour { public ModelContainer Model; public ControllerContainer Controller; public ViewContainer View; private Dictionary<string, UnityEvent> eventDictionary = new Dictionary<string, UnityEvent>(); /// <summary> /// Add listener to a given event. /// </summary> /// <param name="eventName">Name of the event.</param> /// <param name="listener">Callback function.</param> public void AddEventListener(string eventName, UnityAction listener) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.AddListener(listener); } else { e = new UnityEvent(); e.AddListener(listener); eventDictionary.Add(eventName, e); } } /// <summary> /// Remove listener from a given event. /// </summary> /// <param name="eventName">Name of the event.</param> /// <param name="listener">Callback function.</param> public void RemoveEventListener(string eventName, UnityAction listener) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.RemoveListener(listener); } } /// <summary> /// Triggers all registered callbacks of a given event. /// </summary> public void TriggerEvent(string eventName) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.Invoke(); } } }
Fix out of sync bugs
using System.Collections; using System.Collections.Generic; using LiteNetLib; namespace LiteNetLibHighLevel { public class LiteNetLibPlayer { public LiteNetLibGameManager Manager { get; protected set; } public NetPeer Peer { get; protected set; } public long ConnectId { get { return Peer.ConnectId; } } public readonly Dictionary<uint, LiteNetLibIdentity> SpawnedObjects = new Dictionary<uint, LiteNetLibIdentity>(); public LiteNetLibPlayer(LiteNetLibGameManager manager, NetPeer peer) { Manager = manager; Peer = peer; } internal void DestoryAllObjects() { foreach (var spawnedObject in SpawnedObjects) Manager.Assets.NetworkDestroy(spawnedObject.Key); } } }
using System.Collections; using System.Collections.Generic; using LiteNetLib; namespace LiteNetLibHighLevel { public class LiteNetLibPlayer { public LiteNetLibGameManager Manager { get; protected set; } public NetPeer Peer { get; protected set; } public long ConnectId { get { return Peer.ConnectId; } } internal readonly Dictionary<uint, LiteNetLibIdentity> SpawnedObjects = new Dictionary<uint, LiteNetLibIdentity>(); public LiteNetLibPlayer(LiteNetLibGameManager manager, NetPeer peer) { Manager = manager; Peer = peer; } internal void DestoryAllObjects() { var objectIds = new List<uint>(SpawnedObjects.Keys); foreach (var objectId in objectIds) Manager.Assets.NetworkDestroy(objectId); } } }
Fix string format in error message
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZocBuild.Database.Errors { public class MismatchedSchemaError : BuildErrorBase { public MismatchedSchemaError(string objectName, string expected, string actual) { ActualSchemaName = actual; ExpectedSchemaName = expected; ObjectName = objectName; } public string ActualSchemaName { get; private set; } public string ExpectedSchemaName { get; private set; } public string ObjectName { get; private set; } public override string ErrorType { get { return "Mismatched Schema"; } } public override string GetMessage() { return string.Format("Cannot use script of schema {2} for {1} when expecting schema {0}.", ObjectName, ExpectedSchemaName, ActualSchemaName); } public override BuildItem.BuildStatusType Status { get { return BuildItem.BuildStatusType.ScriptError; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZocBuild.Database.Errors { public class MismatchedSchemaError : BuildErrorBase { public MismatchedSchemaError(string objectName, string expected, string actual) { ActualSchemaName = actual; ExpectedSchemaName = expected; ObjectName = objectName; } public string ActualSchemaName { get; private set; } public string ExpectedSchemaName { get; private set; } public string ObjectName { get; private set; } public override string ErrorType { get { return "Mismatched Schema"; } } public override string GetMessage() { return string.Format("Cannot use script of schema {2} for {0} when expecting schema {1}.", ObjectName, ExpectedSchemaName, ActualSchemaName); } public override BuildItem.BuildStatusType Status { get { return BuildItem.BuildStatusType.ScriptError; } } } }
Allow to disable the application-starter
using System.Web; using Microsoft.Web.Infrastructure; namespace BoC.Web { public class ApplicationStarterHttpModule : IHttpModule { private static object lockObject = new object(); private static bool startWasCalled = false; public static void StartApplication() { if (startWasCalled || Initializer.Executed) return; try { lock (lockObject) { if (startWasCalled) return; Initializer.Execute(); startWasCalled = true; } } catch { InfrastructureHelper.UnloadAppDomain(); throw; } } public void Init(HttpApplication context) { context.BeginRequest += (sender, args) => StartApplication(); if (!startWasCalled) { try { context.Application.Lock(); StartApplication(); } finally { context.Application.UnLock(); } } } public void Dispose() { } } }
using System; using System.Configuration; using System.Web; using System.Web.Configuration; using Microsoft.Web.Infrastructure; namespace BoC.Web { public class ApplicationStarterHttpModule : IHttpModule { private static object lockObject = new object(); private static bool startWasCalled = false; public static volatile bool Disabled = false; public static void StartApplication() { if (Disabled || startWasCalled || Initializer.Executed) return; try { lock (lockObject) { var disabled = WebConfigurationManager.AppSettings["BoC.Web.DisableAutoStart"]; if ("true".Equals(disabled, StringComparison.InvariantCultureIgnoreCase)) { Disabled = true; return; } if (startWasCalled) return; Initializer.Execute(); startWasCalled = true; } } catch { InfrastructureHelper.UnloadAppDomain(); throw; } } public void Init(HttpApplication context) { if (Disabled) return; context.BeginRequest += (sender, args) => StartApplication(); if (!Disabled && !startWasCalled) { try { context.Application.Lock(); StartApplication(); } finally { context.Application.UnLock(); } } } public void Dispose() { } } }
Add simple mechanism to fetch JSON and display it
using Android.App; using Android.Widget; using Android.OS; namespace TwitterMonkey { [Activity (Label = "TwitterMonkey", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 1; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.myButton); button.Click += delegate { button.Text = string.Format ("{0} clicks!", count++); }; } } }
using System; using System.IO; using System.Net; using System.Threading.Tasks; using Android.App; using Android.OS; using Android.Widget; using TwitterMonkey.Portable; namespace TwitterMonkey { [Activity(Label = "TwitterMonkey", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { protected override void OnCreate (Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.myButton); button.Click += async (sender, e) => { var textView = FindViewById<TextView>(Resource.Id.textView1); var jsonString = await fetchJsonAsync(new Uri ("http://goo.gl/pJwOUS")); var tweets = TweetConverter.ConvertAll(jsonString); foreach (Tweet t in tweets) { textView.Text += t.Message + "\n"; } }; } private async Task<string> fetchJsonAsync (Uri uri) { HttpWebRequest request = new HttpWebRequest(uri); var resp = await request.GetResponseAsync(); StreamReader reader = new StreamReader (resp.GetResponseStream()); return await reader.ReadToEndAsync(); } } }
Update IAdapter registration in Droid example project
using System; using Android.App; using Android.Content; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Xamarin.Forms; namespace BluetoothLE.Example.Droid { [Activity(Label = "BluetoothLE.Example.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); DependencyService.Register<IAdapter, Adapter>(); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
using System; using Android.App; using Android.Content; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Xamarin.Forms; namespace BluetoothLE.Example.Droid { [Activity(Label = "BluetoothLE.Example.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); DependencyService.Register<BluetoothLE.Core.IAdapter, BluetoothLE.Droid.Adapter>(); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
Fix slider repeat points appearing far too late
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Osu.Objects { public class RepeatPoint : OsuHitObject { public int RepeatIndex { get; set; } public double SpanDuration { get; set; } protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaultsToSelf(controlPointInfo, difficulty); // We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders // we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time. if (RepeatIndex > 0) TimePreempt = Math.Min(SpanDuration * 2, TimePreempt); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Osu.Objects { public class RepeatPoint : OsuHitObject { public int RepeatIndex { get; set; } public double SpanDuration { get; set; } protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaultsToSelf(controlPointInfo, difficulty); // Out preempt should be one span early to give the user ample warning. TimePreempt += SpanDuration; // We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders // we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time. if (RepeatIndex > 0) TimePreempt = Math.Min(SpanDuration * 2, TimePreempt); } } }
Apply naming suppression to allow build to build.
namespace Octokit { public interface IActivitiesClient { IEventsClient Event { get; } } }
namespace Octokit { public interface IActivitiesClient { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Event")] IEventsClient Event { get; } } }
Fix exception when dumping a null parameter
using System; namespace Mios.Localization.Localizers { public class NullLocalizer { public static LocalizedString Instance(string key, params object[] args) { return new LocalizedString(String.Format(key,args), null); } } }
using System; using System.Linq; namespace Mios.Localization.Localizers { public class NullLocalizer { public static LocalizedString Instance(string key, params object[] args) { var parameters = args.Any() ? "["+String.Join(",",args.Select(t=>(t??String.Empty).ToString()).ToArray())+"]" : String.Empty; return new LocalizedString(key+parameters, null); } } }
Change naming in test and add one
namespace Nancy.Linker.Tests { using System.Runtime.InteropServices; using Testing; using Xunit; public class ResourceLinkerTests { private Browser app; public class TestModule : NancyModule { public static ResourceLinker linker; public TestModule(ResourceLinker linker) { TestModule.linker = linker; Get["foo", "/foo"] = _ => 200; Get["bar", "/bar/{id}"] = _ => 200; } } public ResourceLinkerTests() { app = new Browser(with => with.Module<TestModule>(), defaults: to => to.HostName("localhost")); } [Fact] public void Link_generated_is_correct_when_base_uri_has_trailing_slash() { var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "foo", new {}); Assert.Equal("http://localhost/foo", uriString.ToString()); } [Fact] public void Link_generated_is_correct_with_bound_parameter() { var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new {id = 123 }); Assert.Equal("http://localhost/bar/123", uriString.ToString()); } [Fact] public void Argument_exception_is_thrown_if_parameter_from_template_cannot_be_bound() { } } }
namespace Nancy.Linker.Tests { using System; using System.Runtime.InteropServices; using Testing; using Xunit; public class ResourceLinker_Should { private Browser app; public class TestModule : NancyModule { public static ResourceLinker linker; public TestModule(ResourceLinker linker) { TestModule.linker = linker; Get["foo", "/foo"] = _ => 200; Get["bar", "/bar/{id}"] = _ => 200; } } public ResourceLinker_Should() { app = new Browser(with => with.Module<TestModule>(), defaults: to => to.HostName("localhost")); } [Fact] public void generate_absolute_uri_correctly_when_route_has_no_params() { var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "foo", new {}); Assert.Equal("http://localhost/foo", uriString.ToString()); } [Fact] public void generate_absolute_uri_correctly_when_route_has_params() { var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new {id = 123 }); Assert.Equal("http://localhost/bar/123", uriString.ToString()); } [Fact] public void throw_if_parameter_from_template_cannot_be_bound() { Assert.Throws<ArgumentException>(() => TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new { }) ); } } }
Fix bugs that native functions with parameters are not instantiable due to parsing mistakes
using NBi.Core.Transformation.Transformer.Native; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Transformation.Transformer { public class NativeTransformationFactory { public INativeTransformation Instantiate(string code) { var textInfo = CultureInfo.InvariantCulture.TextInfo; var parameters = code.Replace("(", ",") .Replace(")", ",") .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .ToList().Skip(1).Select(x => x.Trim()).ToArray(); var classToken = code.Contains("(") ? code.Replace(" ", "").Substring(0, code.IndexOf('(')) : code; var className = textInfo.ToTitleCase(classToken.Trim().Replace("-", " ")).Replace(" ", "").Replace("Datetime", "DateTime"); var clazz = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetTypes()) .Where( t => t.IsClass && t.IsAbstract == false && t.Name == className && t.GetInterface("INativeTransformation") != null) .SingleOrDefault(); if (clazz == null) throw new NotImplementedTransformationException(className); return (INativeTransformation)Activator.CreateInstance(clazz, parameters); } } }
using NBi.Core.Transformation.Transformer.Native; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Transformation.Transformer { public class NativeTransformationFactory { public INativeTransformation Instantiate(string code) { var textInfo = CultureInfo.InvariantCulture.TextInfo; var parameters = code.Replace("(", ",") .Replace(")", ",") .Replace(" ", "") .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .ToList().Skip(1).Select(x => x.Trim()).ToArray(); var classToken = code.Contains("(") ? code.Replace(" ", "").Substring(0, code.IndexOf('(') - 1) : code; var className = textInfo.ToTitleCase(classToken.Trim().Replace("-", " ")).Replace(" ", "").Replace("Datetime", "DateTime"); var clazz = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetTypes()) .Where( t => t.IsClass && t.IsAbstract == false && t.Name == className && t.GetInterface("INativeTransformation") != null) .SingleOrDefault(); if (clazz == null) throw new NotImplementedTransformationException(className); return (INativeTransformation)Activator.CreateInstance(clazz, parameters); } } }
Fix PartialView Tree Controller to display a folder icon as opposed to an article icon for nested folders - looks odd/broken to me otherwise
using umbraco; using Umbraco.Core.IO; using Umbraco.Web.Composing; using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi.Filters; using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Trees { /// <summary> /// Tree for displaying partial views in the settings app /// </summary> [Tree(Constants.Applications.Settings, Constants.Trees.PartialViews, null, sortOrder: 7)] [UmbracoTreeAuthorize(Constants.Trees.PartialViews)] [PluginController("UmbracoTrees")] [CoreTree(TreeGroup = Constants.Trees.Groups.Templating)] public class PartialViewsTreeController : FileSystemTreeController { protected override IFileSystem FileSystem => Current.FileSystems.PartialViewsFileSystem; private static readonly string[] ExtensionsStatic = {"cshtml"}; protected override string[] Extensions => ExtensionsStatic; protected override string FileIcon => "icon-article"; protected override void OnRenderFolderNode(ref TreeNode treeNode) { //TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now. treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);"; treeNode.Icon = "icon-article"; } } }
using umbraco; using Umbraco.Core.IO; using Umbraco.Web.Composing; using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi.Filters; using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Trees { /// <summary> /// Tree for displaying partial views in the settings app /// </summary> [Tree(Constants.Applications.Settings, Constants.Trees.PartialViews, null, sortOrder: 7)] [UmbracoTreeAuthorize(Constants.Trees.PartialViews)] [PluginController("UmbracoTrees")] [CoreTree(TreeGroup = Constants.Trees.Groups.Templating)] public class PartialViewsTreeController : FileSystemTreeController { protected override IFileSystem FileSystem => Current.FileSystems.PartialViewsFileSystem; private static readonly string[] ExtensionsStatic = {"cshtml"}; protected override string[] Extensions => ExtensionsStatic; protected override string FileIcon => "icon-article"; protected override void OnRenderFolderNode(ref TreeNode treeNode) { //TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now. treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);"; treeNode.Icon = "icon-folder"; } } }
Mark IPublisher<> descriptor as overrider
using System.Collections.Generic; using Elders.Cronus.Discoveries; using Microsoft.Extensions.DependencyInjection; using RabbitMQ.Client; namespace Elders.Cronus.Transport.RabbitMQ { public class RabbitMqPublisherDiscovery : DiscoveryBasedOnExecutingDirAssemblies<IPublisher<IMessage>> { protected override DiscoveryResult<IPublisher<IMessage>> DiscoverFromAssemblies(DiscoveryContext context) { return new DiscoveryResult<IPublisher<IMessage>>(GetModels()); } IEnumerable<DiscoveredModel> GetModels() { yield return new DiscoveredModel(typeof(RabbitMqSettings), typeof(RabbitMqSettings), ServiceLifetime.Singleton); yield return new DiscoveredModel(typeof(IConnectionFactory), typeof(RabbitMqConnectionFactory), ServiceLifetime.Singleton); yield return new DiscoveredModel(typeof(IPublisher<>), typeof(RabbitMqPublisher<>), ServiceLifetime.Singleton); } } }
using System.Collections.Generic; using Elders.Cronus.Discoveries; using Microsoft.Extensions.DependencyInjection; using RabbitMQ.Client; namespace Elders.Cronus.Transport.RabbitMQ { public class RabbitMqPublisherDiscovery : DiscoveryBasedOnExecutingDirAssemblies<IPublisher<IMessage>> { protected override DiscoveryResult<IPublisher<IMessage>> DiscoverFromAssemblies(DiscoveryContext context) { return new DiscoveryResult<IPublisher<IMessage>>(GetModels()); } IEnumerable<DiscoveredModel> GetModels() { yield return new DiscoveredModel(typeof(RabbitMqSettings), typeof(RabbitMqSettings), ServiceLifetime.Singleton); yield return new DiscoveredModel(typeof(IConnectionFactory), typeof(RabbitMqConnectionFactory), ServiceLifetime.Singleton); var publisherModel = new DiscoveredModel(typeof(IPublisher<>), typeof(RabbitMqPublisher<>), ServiceLifetime.Singleton); publisherModel.CanOverrideDefaults = true; yield return publisherModel; } } }
Write JSON as prettified string to file for better readability.
using Newtonsoft.Json; namespace TicketTimer.Core.Infrastructure { public class JsonWorkItemStore : WorkItemStore { private readonly FileStore _fileStore; private const string FileName = "timer.state"; private TimerState _state; public JsonWorkItemStore(FileStore fileStore) { _fileStore = fileStore; Load(); } public void AddToArchive(WorkItem workItem) { GetState().WorkItemArchive.Add(workItem); Save(); } public TimerState GetState() { if (_state == null) { Load(); } return _state; } public void Save() { var json = JsonConvert.SerializeObject(_state); _fileStore.WriteFile(json, FileName); } private void Load() { var json = _fileStore.ReadFile(FileName); if (!string.IsNullOrEmpty(json)) { _state = JsonConvert.DeserializeObject<TimerState>(json); } else { _state = new TimerState(); } } public void SetCurrent(WorkItem workItem) { GetState().CurrentWorkItem = workItem; Save(); } public void ClearArchive() { GetState().WorkItemArchive.Clear(); Save(); } } }
using Newtonsoft.Json; namespace TicketTimer.Core.Infrastructure { public class JsonWorkItemStore : WorkItemStore { private readonly FileStore _fileStore; private const string FileName = "timer.state"; private TimerState _state; public JsonWorkItemStore(FileStore fileStore) { _fileStore = fileStore; Load(); } public void AddToArchive(WorkItem workItem) { GetState().WorkItemArchive.Add(workItem); Save(); } public TimerState GetState() { if (_state == null) { Load(); } return _state; } public void Save() { var json = JsonConvert.SerializeObject(_state, Formatting.Indented); _fileStore.WriteFile(json, FileName); } private void Load() { var json = _fileStore.ReadFile(FileName); if (!string.IsNullOrEmpty(json)) { _state = JsonConvert.DeserializeObject<TimerState>(json); } else { _state = new TimerState(); } } public void SetCurrent(WorkItem workItem) { GetState().CurrentWorkItem = workItem; Save(); } public void ClearArchive() { GetState().WorkItemArchive.Clear(); Save(); } } }
Increase assembly version to 'beta01'
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-alpha01")]
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-beta01")]
Improve comparison order to avoid reading blob values by mistake
using Rainbow.Model; namespace Rainbow.Diff.Fields { public class DefaultComparison : IFieldComparer { public bool CanCompare(IItemFieldValue field1, IItemFieldValue field2) { return field1 != null && field2 != null; } public bool AreEqual(IItemFieldValue field1, IItemFieldValue field2) { if (field1.Value == null || field2.Value == null) return false; if (field1.BlobId.HasValue && field2.BlobId.HasValue) return field1.BlobId.Value.Equals(field2.BlobId.Value); return field1.Value.Equals(field2.Value); } } }
using Rainbow.Model; namespace Rainbow.Diff.Fields { public class DefaultComparison : IFieldComparer { public bool CanCompare(IItemFieldValue field1, IItemFieldValue field2) { return field1 != null && field2 != null; } public bool AreEqual(IItemFieldValue field1, IItemFieldValue field2) { if (field1.BlobId.HasValue && field2.BlobId.HasValue) return field1.BlobId.Value.Equals(field2.BlobId.Value); var field1Value = field1.Value; var field2Value = field2.Value; if (field1Value == null || field2Value == null) return false; return field1Value.Equals(field2Value); } } }
Check InputStream on when seekable.
namespace Simple.Web.Behaviors.Implementations { using MediaTypeHandling; using Behaviors; using Http; /// <summary> /// This type supports the framework directly and should not be used from your code. /// </summary> public static class SetInput { /// <summary> /// This method supports the framework directly and should not be used from your code /// </summary> /// <typeparam name="T">The input model type.</typeparam> /// <param name="handler">The handler.</param> /// <param name="context">The context.</param> public static void Impl<T>(IInput<T> handler, IContext context) { if (context.Request.InputStream.Length == 0) return; var mediaTypeHandlerTable = new MediaTypeHandlerTable(); var mediaTypeHandler = mediaTypeHandlerTable.GetMediaTypeHandler(context.Request.GetContentType()); handler.Input = (T)mediaTypeHandler.Read(context.Request.InputStream, typeof(T)); } } }
namespace Simple.Web.Behaviors.Implementations { using MediaTypeHandling; using Behaviors; using Http; /// <summary> /// This type supports the framework directly and should not be used from your code. /// </summary> public static class SetInput { /// <summary> /// This method supports the framework directly and should not be used from your code /// </summary> /// <typeparam name="T">The input model type.</typeparam> /// <param name="handler">The handler.</param> /// <param name="context">The context.</param> public static void Impl<T>(IInput<T> handler, IContext context) { if (context.Request.InputStream.CanSeek && context.Request.InputStream.Length == 0) { return; } var mediaTypeHandlerTable = new MediaTypeHandlerTable(); var mediaTypeHandler = mediaTypeHandlerTable.GetMediaTypeHandler(context.Request.GetContentType()); handler.Input = (T)mediaTypeHandler.Read(context.Request.InputStream, typeof(T)); } } }
Fix bug with require token field in register page
namespace Application.Business.Models { using System.ComponentModel.DataAnnotations; public class ResetPasswordFromMailModel { [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] [Display(Name = "Token")] public string Token { get; set; } } }
namespace Application.Business.Models { using System.ComponentModel.DataAnnotations; public class ResetPasswordFromMailModel { [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Display(Name = "Token")] public string Token { get; set; } } }
Remove box surrounding close button
// 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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Overlays.Chat.ChannelList { public class ChannelListItemCloseButton : OsuAnimatedButton { [BackgroundDependencyLoader] private void load(OsuColour osuColour) { Alpha = 0f; Size = new Vector2(20); Add(new SpriteIcon { Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(0.75f), Icon = FontAwesome.Solid.TimesCircle, RelativeSizeAxes = Axes.Both, Colour = osuColour.Red1, }); } } }
// 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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.Chat.ChannelList { public class ChannelListItemCloseButton : OsuClickableContainer { private SpriteIcon icon = null!; private Color4 normalColour; private Color4 hoveredColour; [BackgroundDependencyLoader] private void load(OsuColour osuColour) { normalColour = osuColour.Red2; hoveredColour = Color4.White; Alpha = 0f; Size = new Vector2(20); Add(icon = new SpriteIcon { Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(0.75f), Icon = FontAwesome.Solid.TimesCircle, RelativeSizeAxes = Axes.Both, Colour = normalColour, }); } // Transforms matching OsuAnimatedButton protected override bool OnHover(HoverEvent e) { icon.FadeColour(hoveredColour, 300, Easing.OutQuint); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { icon.FadeColour(normalColour, 300, Easing.OutQuint); base.OnHoverLost(e); } protected override bool OnMouseDown(MouseDownEvent e) { icon.ScaleTo(0.75f, 2000, Easing.OutQuint); return base.OnMouseDown(e); } protected override void OnMouseUp(MouseUpEvent e) { icon.ScaleTo(1, 1000, Easing.OutElastic); base.OnMouseUp(e); } } }
Add support for searching beatmap author at song select
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using SQLite.Net.Attributes; namespace osu.Game.Database { public class BeatmapMetadata { [PrimaryKey, AutoIncrement] public int ID { get; set; } public int? OnlineBeatmapSetID { get; set; } public string Title { get; set; } public string TitleUnicode { get; set; } public string Artist { get; set; } public string ArtistUnicode { get; set; } public string Author { get; set; } public string Source { get; set; } public string Tags { get; set; } public int PreviewTime { get; set; } public string AudioFile { get; set; } public string BackgroundFile { get; set; } public string[] SearchableTerms => new[] { Artist, ArtistUnicode, Title, TitleUnicode, Source, Tags }.Where(s => !string.IsNullOrEmpty(s)).ToArray(); } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using SQLite.Net.Attributes; namespace osu.Game.Database { public class BeatmapMetadata { [PrimaryKey, AutoIncrement] public int ID { get; set; } public int? OnlineBeatmapSetID { get; set; } public string Title { get; set; } public string TitleUnicode { get; set; } public string Artist { get; set; } public string ArtistUnicode { get; set; } public string Author { get; set; } public string Source { get; set; } public string Tags { get; set; } public int PreviewTime { get; set; } public string AudioFile { get; set; } public string BackgroundFile { get; set; } public string[] SearchableTerms => new[] { Author, Artist, ArtistUnicode, Title, TitleUnicode, Source, Tags }.Where(s => !string.IsNullOrEmpty(s)).ToArray(); } }
Fix bug when hitting Enter on last row (PG-234)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SIL.Windows.Forms.Widgets.BetterGrid; namespace Glyssen.Controls { //DataGridView with Enter moving to right (instead of down) public class DataGridViewOverrideEnter : BetterGrid { public DataGridViewOverrideEnter() { AllowUserToAddRows = true; MultiSelect = true; } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.Enter) { MoveToNextField(); return true; } return base.ProcessCmdKey(ref msg, keyData); } public void MoveToNextField() { int nextColumn, nextRow; if (CurrentCell.ColumnIndex + 1 < ColumnCount) { nextColumn = CurrentCell.ColumnIndex + 1; nextRow = CurrentCell.RowIndex; } else { nextColumn = 0; nextRow = CurrentCell.RowIndex + 1; } CurrentCell = Rows[nextRow].Cells[nextColumn]; } private void InitializeComponent() { ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); this.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); this.ResumeLayout(false); } } }
using System.Windows.Forms; using SIL.Windows.Forms.Widgets.BetterGrid; namespace Glyssen.Controls { /// <summary> /// DataGridView with Enter moving to right (instead of down) /// </summary> public class DataGridViewOverrideEnter : BetterGrid { public DataGridViewOverrideEnter() { AllowUserToAddRows = true; MultiSelect = true; } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.Enter) { MoveToNextField(); return true; } return base.ProcessCmdKey(ref msg, keyData); } public void MoveToNextField() { int nextColumn, nextRow; if (CurrentCell.ColumnIndex + 1 < ColumnCount) { nextColumn = CurrentCell.ColumnIndex + 1; nextRow = CurrentCell.RowIndex; } else if (CurrentCell.RowIndex + 1 < RowCount) { nextColumn = 0; nextRow = CurrentCell.RowIndex + 1; } else { return; } CurrentCell = Rows[nextRow].Cells[nextColumn]; } } }
Fix press space to start game launch bomb
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpecialPower : MonoBehaviour { public float manaCost; public float coolDownDuration; public string button; public bool isBomb = false; //tmp [HideInInspector] public float mana; public float maxMana; public float coolDownTimer = 0; private ISpecialPower power; void Start () { power = GetComponent<ISpecialPower>(); if(!isBomb) { maxMana = transform.parent.GetComponent<Player>().maxMana; //tmp } mana = maxMana; NotifyUI(); } // Update is called once per frame void Update () { coolDownTimer -= Time.deltaTime; if(Input.GetButtonDown(button)) { if (coolDownTimer < 0 && mana >= manaCost) { power.Activate(); coolDownTimer = coolDownDuration; mana -= manaCost; NotifyUI(); } else { SoundManager.instance.PlaySound(GenericSoundsEnum.ERROR); } } } private void NotifyUI() { if (isBomb) { BombUI.instance.OnUsePower(this); } else { PowerUI.instance.OnUsePower(this); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpecialPower : MonoBehaviour { public float manaCost; public float coolDownDuration; public string button; public bool isBomb = false; //tmp [HideInInspector] public float mana; public float maxMana; public float coolDownTimer = 0; private ISpecialPower power; void Start () { power = GetComponent<ISpecialPower>(); if(!isBomb) { maxMana = transform.parent.GetComponent<Player>().maxMana; //tmp } mana = maxMana; NotifyUI(); enabled = false; EventDispatcher.AddEventListener(Events.GAME_LOADED, OnLoaded); } void OnDestroy() { EventDispatcher.RemoveEventListener(Events.GAME_LOADED, OnLoaded); } private void OnLoaded(object useless) { enabled = true; } // Update is called once per frame void Update () { coolDownTimer -= Time.deltaTime; if(Input.GetButtonDown(button)) { if (coolDownTimer < 0 && mana >= manaCost) { power.Activate(); coolDownTimer = coolDownDuration; mana -= manaCost; NotifyUI(); } else { SoundManager.instance.PlaySound(GenericSoundsEnum.ERROR); } } } private void NotifyUI() { if (isBomb) { BombUI.instance.OnUsePower(this); } else { PowerUI.instance.OnUsePower(this); } } }
Fix overlay hide animation playing at the wrong point in time.
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Graphics.Containers; using System.Linq; namespace osu.Framework.Graphics.Performance { class PerformanceOverlay : FlowContainer, IStateful<FrameStatisticsMode> { private FrameStatisticsMode state; public FrameStatisticsMode State { get { return state; } set { if (state == value) return; state = value; switch (state) { case FrameStatisticsMode.None: FadeOut(100); break; case FrameStatisticsMode.Minimal: case FrameStatisticsMode.Full: FadeIn(100); foreach (FrameStatisticsDisplay d in Children.Cast<FrameStatisticsDisplay>()) d.State = state; break; } } } public override void Load(BaseGame game) { base.Load(game); Add(new FrameStatisticsDisplay(@"Input", game.Host.InputMonitor)); Add(new FrameStatisticsDisplay(@"Update", game.Host.UpdateMonitor)); Add(new FrameStatisticsDisplay(@"Draw", game.Host.DrawMonitor)); Direction = FlowDirection.VerticalOnly; } } public enum FrameStatisticsMode { None, Minimal, Full } }
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Graphics.Containers; using System.Linq; namespace osu.Framework.Graphics.Performance { class PerformanceOverlay : FlowContainer, IStateful<FrameStatisticsMode> { private FrameStatisticsMode state; public FrameStatisticsMode State { get { return state; } set { if (state == value) return; state = value; switch (state) { case FrameStatisticsMode.None: FadeOut(100); break; case FrameStatisticsMode.Minimal: case FrameStatisticsMode.Full: FadeIn(100); break; } foreach (FrameStatisticsDisplay d in Children.Cast<FrameStatisticsDisplay>()) d.State = state; } } public override void Load(BaseGame game) { base.Load(game); Add(new FrameStatisticsDisplay(@"Input", game.Host.InputMonitor)); Add(new FrameStatisticsDisplay(@"Update", game.Host.UpdateMonitor)); Add(new FrameStatisticsDisplay(@"Draw", game.Host.DrawMonitor)); Direction = FlowDirection.VerticalOnly; } } public enum FrameStatisticsMode { None, Minimal, Full } }
Add annotation to DHtml enum
#region License /* Copyright [2011] [Jeffrey Cameron] 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. */ #endregion using System; using System.ComponentModel; namespace PicklesDoc.Pickles { public enum DocumentationFormat { [Description("HTML")] Html, [Description("Microsoft Word OpenXML (.docx)")] Word, [Description("Darwin Information Typing Architecture (DITA)")] Dita, [Description("Javascript Object Notation (JSON)")] JSON, [Description("Microsoft Excel OpenXML (.xlsx)")] Excel, DHtml } }
#region License /* Copyright [2011] [Jeffrey Cameron] 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. */ #endregion using System; using System.ComponentModel; namespace PicklesDoc.Pickles { public enum DocumentationFormat { [Description("HTML")] Html, [Description("Microsoft Word OpenXML (.docx)")] Word, [Description("Darwin Information Typing Architecture (DITA)")] Dita, [Description("Javascript Object Notation (JSON)")] JSON, [Description("Microsoft Excel OpenXML (.xlsx)")] Excel, [Description("HTML w/search")] DHtml } }
Fix text translations to be non-blocking
#region Copyright (c) 2016 Atif Aziz. All rights reserved. // // 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. // #endregion namespace WebLinq.Text { using System; using System.Net.Http; using System.Reactive.Linq; using System.Text; public static class TextQuery { public static IObservable<string> Delimited<T>(this IObservable<T> query, string delimiter) => query.Aggregate(new StringBuilder(), (sb, e) => sb.Append(e), sb => sb.ToString()); public static IObservable<HttpFetch<string>> Text(this IObservable<HttpFetch<HttpContent>> query) => // TODO fix to be non-blocking from fetch in query select fetch.WithContent(fetch.Content.ReadAsStringAsync().Result); } }
#region Copyright (c) 2016 Atif Aziz. All rights reserved. // // 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. // #endregion namespace WebLinq.Text { using System; using System.Net.Http; using System.Reactive.Linq; using System.Text; public static class TextQuery { public static IObservable<string> Delimited<T>(this IObservable<T> query, string delimiter) => query.Aggregate(new StringBuilder(), (sb, e) => sb.Append(e), sb => sb.ToString()); public static IObservable<HttpFetch<string>> Text(this IObservable<HttpFetch<HttpContent>> query) => from fetch in query from text in fetch.Content.ReadAsStringAsync() select fetch.WithContent(text); } }
Make the example html.cshtml a little more relevant
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CefSharp.Own.Example.Wpf</title> </head> <body> <header> <h1>@Model.Text</h1> </header> <section> <h2>Backlog</h2> <ul class="bugs" id="backlog"> <li>a bug</li> </ul> </section> <section> <h2>Working</h2> <ul class="bugs" id="working"> <li>a bug</li> </ul> </section> <section> <h2>Done</h2> <ul class="bugs" id="done"> <li>a bug</li> </ul> </section> </body> </html>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CefSharp.Own.Example.Wpf</title> </head> <body> <header> <h1>@Model.Text</h1> </header> <section> <h2>CefSharp + OWIN + Nancy + Razor</h2> <ul> <li>No network requests are made, just in memory requests to the OWIN pipeline</li> <li>CefSharp.Owin has no reference to OWIN, just the known Func type that it uses</li> <li>This request was rendered using Nancy and the Razor view engine</li> <li>TODO</li> </ul> </section> </body> </html>
Include URI in DataPackage when sharing a skin
using DataDragon; using LolHandbook.ViewModels; using System; using System.Collections.Generic; using Windows.ApplicationModel.DataTransfer; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace LolHandbook.Pages { public sealed partial class ChampionSkinsPage : Page, ISupportSharing { public ChampionSkinsPage() { this.InitializeComponent(); } private ChampionSkinsViewModel ViewModel => DataContext as ChampionSkinsViewModel; protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (e.Parameter is IList<ChampionSkin>) { ViewModel.Skins = (IList<ChampionSkin>)e.Parameter; } } public void OnDataRequested(DataRequest request) { request.Data.Properties.Title = ViewModel.CurrentSkinName; DataRequestDeferral deferral = request.GetDeferral(); try { string filename = ViewModel.CurrentSkinName + ".jpg"; Uri uri = ViewModel.CurrentSkinUri; RandomAccessStreamReference streamReference = RandomAccessStreamReference.CreateFromUri(uri); request.Data.Properties.Thumbnail = streamReference; request.Data.SetBitmap(streamReference); } finally { deferral.Complete(); } } private void Share_Click(object sender, RoutedEventArgs e) { DataTransferManager.ShowShareUI(); } } }
using DataDragon; using LolHandbook.ViewModels; using System; using System.Collections.Generic; using Windows.ApplicationModel.DataTransfer; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace LolHandbook.Pages { public sealed partial class ChampionSkinsPage : Page, ISupportSharing { public ChampionSkinsPage() { this.InitializeComponent(); } private ChampionSkinsViewModel ViewModel => DataContext as ChampionSkinsViewModel; protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (e.Parameter is IList<ChampionSkin>) { ViewModel.Skins = (IList<ChampionSkin>)e.Parameter; } } public void OnDataRequested(DataRequest request) { request.Data.Properties.Title = ViewModel.CurrentSkinName; request.Data.SetUri(ViewModel.CurrentSkinUri); DataRequestDeferral deferral = request.GetDeferral(); try { string filename = ViewModel.CurrentSkinName + ".jpg"; Uri uri = ViewModel.CurrentSkinUri; RandomAccessStreamReference streamReference = RandomAccessStreamReference.CreateFromUri(uri); request.Data.Properties.Thumbnail = streamReference; request.Data.SetBitmap(streamReference); } finally { deferral.Complete(); } } private void Share_Click(object sender, RoutedEventArgs e) { DataTransferManager.ShowShareUI(); } } }
Update test case to suit test data
using NUnit.Framework; using System; using System.IO; using Time_Table_Arranging_Program; using Time_Table_Arranging_Program.Class; namespace NUnit.Tests2 { [TestFixture] public class Test_StartDateEndDateFinder { string input = Helper.RawStringOfTestFile("SampleData-FAM-2017-2ndSem.html"); [Test] public void Test_1() { var parser = new StartDateEndDateFinder(input); Assert.True(parser.GetStartDate() == new DateTime(2017 , 5 , 29 , 0 , 0 , 0)); Assert.True(parser.GetEndDate() == new DateTime(2017 , 9 , 3 , 0 , 0 , 0)); } } }
using NUnit.Framework; using System; using System.IO; using Time_Table_Arranging_Program; using Time_Table_Arranging_Program.Class; namespace NUnit.Tests2 { [TestFixture] public class Test_StartDateEndDateFinder { string input = Helper.RawStringOfTestFile("SampleData-FAM-2017-2ndSem.html"); [Test] public void Test_1() { var parser = new StartDateEndDateFinder(input); Assert.True(parser.GetStartDate() == new DateTime(2017 , 10 , 16 , 0 , 0 , 0)); Assert.True(parser.GetEndDate() == new DateTime(2017 , 12 , 3 , 0 , 0 , 0)); } } }
Improve test to avoid potential race condition
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Wcf.Tests.Channels; using Microsoft.ApplicationInsights.Wcf.Tests.Service; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; namespace Microsoft.ApplicationInsights.Wcf.Tests.Integration { [TestClass] public class OneWayTests { [TestMethod] [TestCategory("Integration"), TestCategory("One-Way")] public void SuccessfulOneWayCallGeneratesRequestEvent() { TestTelemetryChannel.Clear(); using ( var host = new HostingContext<OneWayService, IOneWayService>() ) { host.Open(); IOneWayService client = host.GetChannel(); client.SuccessfullOneWayCall(); } var req = TestTelemetryChannel.CollectedData() .FirstOrDefault(x => x is RequestTelemetry); Assert.IsNotNull(req); } [TestMethod] [TestCategory("Integration"), TestCategory("One-Way")] public void FailedOneWayCallGeneratesExceptionEvent() { TestTelemetryChannel.Clear(); var host = new HostingContext<OneWayService, IOneWayService>() .ExpectFailure(); using ( host ) { host.Open(); IOneWayService client = host.GetChannel(); try { client.FailureOneWayCall(); } catch { } } var req = TestTelemetryChannel.CollectedData() .FirstOrDefault(x => x is ExceptionTelemetry); Assert.IsNotNull(req); } } }
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Wcf.Tests.Channels; using Microsoft.ApplicationInsights.Wcf.Tests.Service; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; namespace Microsoft.ApplicationInsights.Wcf.Tests.Integration { [TestClass] public class OneWayTests { [TestMethod] [TestCategory("Integration"), TestCategory("One-Way")] public void SuccessfulOneWayCallGeneratesRequestEvent() { TestTelemetryChannel.Clear(); using ( var host = new HostingContext<OneWayService, IOneWayService>() ) { host.Open(); IOneWayService client = host.GetChannel(); client.SuccessfullOneWayCall(); } var req = TestTelemetryChannel.CollectedData() .FirstOrDefault(x => x is RequestTelemetry); Assert.IsNotNull(req); } [TestMethod] [TestCategory("Integration"), TestCategory("One-Way")] public void FailedOneWayCallGeneratesExceptionEvent() { TestTelemetryChannel.Clear(); var host = new HostingContext<OneWayService, IOneWayService>() .ExpectFailure().ShouldWaitForCompletion(); using ( host ) { host.Open(); IOneWayService client = host.GetChannel(); try { client.FailureOneWayCall(); } catch { } } var req = TestTelemetryChannel.CollectedData() .FirstOrDefault(x => x is ExceptionTelemetry); Assert.IsNotNull(req); } } }
Throw an exception if InnerResolve returns null
using System; using System.Collections.Generic; using Mono.Cecil; public partial class ModuleWeaver { Dictionary<string, TypeDefinition> definitions = new Dictionary<string, TypeDefinition>(); public TypeDefinition Resolve(TypeReference reference) { TypeDefinition definition; if (definitions.TryGetValue(reference.FullName, out definition)) { return definition; } return definitions[reference.FullName] = InnerResolve(reference); } static TypeDefinition InnerResolve(TypeReference reference) { try { return reference.Resolve(); } catch (Exception exception) { throw new Exception($"Could not resolve '{reference.FullName}'.", exception); } } }
using System; using System.Collections.Generic; using Mono.Cecil; public partial class ModuleWeaver { Dictionary<string, TypeDefinition> definitions = new Dictionary<string, TypeDefinition>(); public TypeDefinition Resolve(TypeReference reference) { TypeDefinition definition; if (definitions.TryGetValue(reference.FullName, out definition)) { return definition; } return definitions[reference.FullName] = InnerResolve(reference); } static TypeDefinition InnerResolve(TypeReference reference) { TypeDefinition result = null; try { result = reference.Resolve(); } catch (Exception exception) { throw new Exception($"Could not resolve '{reference.FullName}'.", exception); } if(result == null) { throw new Exception($"Could not resolve '{reference.FullName}'."); } return result; } }
Increase size since we add something to the max. 20 chars coming from the request.
using System; using System.ComponentModel.DataAnnotations; namespace HelloCoreClrApp.Data.Entities { public class Greeting { [Key] public Guid GreetingId { get; set; } [Required] [MaxLength(20)] public string Name { get; set; } [Required] public DateTime TimestampUtc { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; namespace HelloCoreClrApp.Data.Entities { public class Greeting { [Key] public Guid GreetingId { get; set; } [Required] [MaxLength(30)] public string Name { get; set; } [Required] public DateTime TimestampUtc { get; set; } } }
Work begin on program to test different algorithms for shifting arrays
// Program for rotating arrays using different Algorithms using System; using System.Linq; public class RotateArray { public static void Main() { // Reads ints from the Console and converts them to an array of ints Console.WriteLine("Please enter array of integers (integers separated by spaces)"); var intArray = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); // Alternative syntaxis without Linq //var intArray = Array.ConvertAll(Console.ReadLine() // .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries), int.Parse); } }
// Program for rotating arrays using different Algorithms using System; using System.Linq; public class RotateArray { public static void Main() { // Reads ints from the Console and converts them to an array of ints Console.WriteLine("Please enter array of integers (integers separated by spaces)"); var intArray = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); // Alternative syntaxis without Linq //var intArray = Array.ConvertAll(Console.ReadLine() // .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries), int.Parse); Console.WriteLine("Enter the number of positions to be shifted"); int d = int.Parse(Console.ReadLine()) % intArray.Length; if (d != 0) SubsetRotation(intArray, d); Console.WriteLine(string.Join(" ", intArray)); } public static void SubsetRotation(int[] array, int d) { int arraySubsetsNumber = EuclideanAlgorithm(array.Length, d); for (int i = 0; i < arraySubsetsNumber; i++) { if (arraySubsetsNumber > 1) { ///////////////////// } else { d = Math.Abs(array.Length - d); for (int k = 0; k < array.Length; k++) { int position = (k * d + d) % array.Length; int temp = array[0]; array[0] = array[position]; array[position] = temp; } } } } //Euclidian algorithm to determine the greatest common divisor public static int EuclideanAlgorithm(int m, int n) { m = m % n; if (m == 0) { return n; } else { return EuclideanAlgorithm(n, m); } } }
Remove Account from the filter state persistence
using System; using BudgetAnalyser.Engine.BankAccount; using Rees.UserInteraction.Contracts; namespace BudgetAnalyser.Engine.Statement { public class PersistentFiltersV1 : IPersistent { public Account Account { get; set; } public DateTime? BeginDate { get; set; } public DateTime? EndDate { get; set; } public int LoadSequence => 50; } }
using System; using Rees.UserInteraction.Contracts; namespace BudgetAnalyser.Engine.Statement { public class PersistentFiltersV1 : IPersistent { public DateTime? BeginDate { get; set; } public DateTime? EndDate { get; set; } public int LoadSequence => 50; } }
Add target property for InvokeMethod markup extension
using Sakuno.UserInterface.ObjectOperations; using System; using System.Windows.Data; using System.Windows.Markup; namespace Sakuno.UserInterface.Commands { public class InvokeMethodExtension : MarkupExtension { string r_Method; object r_Parameter; public InvokeMethodExtension(string rpMethod) : this(rpMethod, null) { } public InvokeMethodExtension(string rpMethod, object rpParameter) { r_Method = rpMethod; r_Parameter = rpParameter; } public override object ProvideValue(IServiceProvider rpServiceProvider) { var rInvokeMethod = new InvokeMethod() { Method = r_Method }; if (r_Parameter != null) { var rParameter = new MethodParameter(); var rBinding = r_Parameter as Binding; if (rBinding == null) rParameter.Value = r_Parameter; else BindingOperations.SetBinding(rParameter, MethodParameter.ValueProperty, rBinding); rInvokeMethod.Parameters.Add(rParameter); } return new ObjectOperationCommand() { Operations = { rInvokeMethod } }; } } }
using Sakuno.UserInterface.ObjectOperations; using System; using System.Windows.Data; using System.Windows.Markup; namespace Sakuno.UserInterface.Commands { public class InvokeMethodExtension : MarkupExtension { string r_Method; object r_Parameter; public object Target { get; set; } public InvokeMethodExtension(string rpMethod) : this(rpMethod, null) { } public InvokeMethodExtension(string rpMethod, object rpParameter) { r_Method = rpMethod; r_Parameter = rpParameter; } public override object ProvideValue(IServiceProvider rpServiceProvider) { var rInvokeMethod = new InvokeMethod() { Method = r_Method }; if (r_Parameter != null) { var rParameter = new MethodParameter(); var rBinding = r_Parameter as Binding; if (rBinding == null) rParameter.Value = r_Parameter; else BindingOperations.SetBinding(rParameter, MethodParameter.ValueProperty, rBinding); rInvokeMethod.Parameters.Add(rParameter); } if (Target != null) { var rBinding = Target as Binding; if (rBinding != null) BindingOperations.SetBinding(rInvokeMethod, InvokeMethod.TargetProperty, rBinding); else rInvokeMethod.Target = Target; } return new ObjectOperationCommand() { Operations = { rInvokeMethod } }; } } }
Add possible (insecure) fix for anti forgery token error: suppress identity heuristics
using System; using System.Threading; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Security; using System.Web.Routing; using WebMatrix.WebData; using Zk.Models; namespace Zk { public class MvcApplication : HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute ("{resource}.axd/{*pathInfo}"); routes.MapRoute ( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); } protected void Application_Start() { if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("ZkTestDatabaseConnection", "Users", "UserId", "Name", autoCreateTables: true); } AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
using System.Web; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using WebMatrix.WebData; namespace Zk { public class MvcApplication : HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute ("{resource}.axd/{*pathInfo}"); routes.MapRoute ( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); } protected void Application_Start() { if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("ZkTestDatabaseConnection", "Users", "UserId", "Name", autoCreateTables: true); } // Insecure fix for anti forgery token exception. // See stackoverflow.com/questions/2206595/how-do-i-solve-an-antiforgerytoken-exception-that-occurs-after-an-iisreset-in-my#20421618 AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
Fix version number 2.0.3.0 => 2.0.3
using System.Resources; using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Configgy")] [assembly: AssemblyDescription("Configgy: Configuration library for .NET")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Configgy")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("2.0.3.0")] [assembly: AssemblyFileVersion("2.0.3.0")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("2.0.3.0")]
using System.Resources; using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Configgy")] [assembly: AssemblyDescription("Configgy: Configuration library for .NET")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Configgy")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("2.0.3.0")] [assembly: AssemblyFileVersion("2.0.3.0")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("2.0.3")]
Switch to kanban by status
@{ ViewBag.Title = "Purchase Order Tracker"; } <div class="page-header"> <h1>@ViewBag.Title</h1> </div> <div class="btn-group"> @Html.ActionLink("Add New", "Create", "PurchaseOrders", null, new { @class = "btn btn-default" }) </div> <!-- AirTable Embed Script for List --> <iframe class="airtable-embed" src="https://airtable.com/embed/shr0Oyic09SX3DbSN?backgroundColor=gray&viewControls=on" frameborder="0" onmousewheel="" width="100%" height="533" style="background: transparent; border: 1px solid #ccc;"></iframe>
@{ ViewBag.Title = "Purchase Order Tracker"; } <div class="page-header"> <h1>@ViewBag.Title</h1> </div> <div class="btn-group"> @Html.ActionLink("Add New", "Create", "PurchaseOrders", null, new { @class = "btn btn-default" }) </div> <!-- AirTable Embed Script for List --> <iframe class="airtable-embed" src="https://airtable.com/embed/shrnIihqGHfCKkOvp?backgroundColor=gray&viewControls=on" frameborder="0" onmousewheel="" width="100%" height="533" style="background: transparent; border: 1px solid #ccc;"></iframe>
Fix ChildrenOfType<> early exit for matching types
// 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.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Framework.Testing { public static class TestingExtensions { /// <summary> /// Find all children recursively of a specific type. As this is expensive and dangerous, it should only be used for testing purposes. /// </summary> public static IEnumerable<T> ChildrenOfType<T>(this Drawable drawable) where T : Drawable { switch (drawable) { case T found: yield return found; break; case CompositeDrawable composite: foreach (var child in composite.InternalChildren) { foreach (var found in child.ChildrenOfType<T>()) yield return found; } break; } } } }
// 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.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Framework.Testing { public static class TestingExtensions { /// <summary> /// Find all children recursively of a specific type. As this is expensive and dangerous, it should only be used for testing purposes. /// </summary> public static IEnumerable<T> ChildrenOfType<T>(this Drawable drawable) where T : Drawable { switch (drawable) { case T found: yield return found; if (found is CompositeDrawable foundComposite) { foreach (var foundChild in handleComposite(foundComposite)) yield return foundChild; } break; case CompositeDrawable composite: foreach (var found in handleComposite(composite)) yield return found; break; } static IEnumerable<T> handleComposite(CompositeDrawable composite) { foreach (var child in composite.InternalChildren) { foreach (var found in child.ChildrenOfType<T>()) yield return found; } } } } }
Put link on the product view for subscription.
@model ICollection<CountryFood.Web.ViewModels.ProductViewModel> <h3>Products</h3> @foreach (var product in Model) { <div class="panel panel-body"> <div> <a href="">@product.Name</a> </div> <div> <span>Votes: </span> @(int.Parse(product.PositiveVotes) + int.Parse(product.NegativeVotes)) </div> <div> <span>Number of subscriptions: </span> @product.NumberOfSubscriptions </div> <div> <span>By: </span>@product.Producer </div> </div> }
@model ICollection<CountryFood.Web.ViewModels.ProductViewModel> <h3>Products</h3> @foreach (var product in Model) { <div class="panel panel-body"> <div> <a href="">@product.Name</a> </div> <div> <span>Votes: </span> @(int.Parse(product.PositiveVotes) + int.Parse(product.NegativeVotes)) </div> <div> <span>Number of subscriptions: </span> @product.NumberOfSubscriptions </div> <div> <span>By: </span>@product.Producer </div> <div> @Html.ActionLink("Subscribe", "Create", "Subscriptions", new { productId = @product.Id }, new { }) </div> </div> }
Adjust polymorphism rules for base class
using System; using System.Collections.Generic; using System.IdentityModel.Tokens; using System.Security.Claims; namespace SnapMD.VirtualCare.LeopardonSso { public abstract class AbstractJwt { protected readonly JwtSecurityTokenHandler SecurityTokenHandler = new JwtSecurityTokenHandler(); protected abstract string Audience { get; } protected abstract string Issuer { get; } protected virtual SignatureProvider SignatureProvider => null; protected abstract SigningCredentials SigningCredentials { get; } protected virtual TokenValidationParameters TokenValidationParameters => new TokenValidationParameters { ValidAudience = Audience, ValidIssuer = Issuer }; public virtual ClaimsPrincipal Parse(string token) { SecurityToken securityToken; return SecurityTokenHandler.ValidateToken(token, TokenValidationParameters, out securityToken); } protected virtual string CreateToken(List<Claim> claims, bool encrypted = true) { if (claims == null) { throw new ArgumentNullException("claims"); } var token = SecurityTokenHandler.CreateToken( subject: new ClaimsIdentity(claims), audience: Audience, issuer: Issuer, signingCredentials: SigningCredentials, signatureProvider: SignatureProvider); return encrypted ? SecurityTokenHandler.WriteToken(token) : token.ToString(); } } }
using System; using System.Collections.Generic; using System.IdentityModel.Tokens; using System.Security.Claims; namespace SnapMD.VirtualCare.LeopardonSso { public abstract class AbstractJwt { protected readonly JwtSecurityTokenHandler SecurityTokenHandler = new JwtSecurityTokenHandler(); protected virtual string Audience { get; } protected virtual string Issuer { get; } protected virtual SignatureProvider SignatureProvider => null; protected abstract SigningCredentials SigningCredentials { get; } protected virtual TokenValidationParameters TokenValidationParameters => new TokenValidationParameters { ValidAudience = Audience, ValidIssuer = Issuer }; public virtual ClaimsPrincipal Parse(string token) { SecurityToken securityToken; return SecurityTokenHandler.ValidateToken(token, TokenValidationParameters, out securityToken); } protected virtual string CreateToken(List<Claim> claims, bool encrypted = true) { if (claims == null) { throw new ArgumentNullException("claims"); } var token = SecurityTokenHandler.CreateToken( subject: new ClaimsIdentity(claims), audience: Audience, issuer: Issuer, signingCredentials: SigningCredentials, signatureProvider: SignatureProvider); return encrypted ? SecurityTokenHandler.WriteToken(token) : token.ToString(); } } }
Allow tracking from old Discord domain in the app (discordapp.com)
using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using DHT.Server.Database; using DHT.Server.Endpoints; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace DHT.Server.Service { public class Startup { public void ConfigureServices(IServiceCollection services) { services.Configure<JsonOptions>(options => { options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict; }); services.AddCors(cors => { cors.AddDefaultPolicy(builder => { builder.WithOrigins("https://discord.com").AllowCredentials().AllowAnyMethod().AllowAnyHeader(); }); }); } [SuppressMessage("ReSharper", "UnusedMember.Global")] public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime, IDatabaseFile db, ServerParameters parameters) { app.UseRouting(); app.UseCors(); app.UseEndpoints(endpoints => { TrackChannelEndpoint trackChannel = new(db, parameters); endpoints.MapPost("/track-channel", async context => await trackChannel.Handle(context)); TrackUsersEndpoint trackUsers = new(db, parameters); endpoints.MapPost("/track-users", async context => await trackUsers.Handle(context)); TrackMessagesEndpoint trackMessages = new(db, parameters); endpoints.MapPost("/track-messages", async context => await trackMessages.Handle(context)); }); } } }
using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using DHT.Server.Database; using DHT.Server.Endpoints; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace DHT.Server.Service { public class Startup { public void ConfigureServices(IServiceCollection services) { services.Configure<JsonOptions>(options => { options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict; }); services.AddCors(cors => { cors.AddDefaultPolicy(builder => { builder.WithOrigins("https://discord.com", "https://discordapp.com").AllowCredentials().AllowAnyMethod().AllowAnyHeader(); }); }); } [SuppressMessage("ReSharper", "UnusedMember.Global")] public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime, IDatabaseFile db, ServerParameters parameters) { app.UseRouting(); app.UseCors(); app.UseEndpoints(endpoints => { TrackChannelEndpoint trackChannel = new(db, parameters); endpoints.MapPost("/track-channel", async context => await trackChannel.Handle(context)); TrackUsersEndpoint trackUsers = new(db, parameters); endpoints.MapPost("/track-users", async context => await trackUsers.Handle(context)); TrackMessagesEndpoint trackMessages = new(db, parameters); endpoints.MapPost("/track-messages", async context => await trackMessages.Handle(context)); }); } } }
Make mania scroll downwards by default
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Configuration.Tracking; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Configuration { public class ManiaConfigManager : RulesetConfigManager<ManiaSetting> { public ManiaConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null) : base(settings, ruleset, variant) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); Set(ManiaSetting.ScrollTime, 1500.0, 50.0, 10000.0, 50.0); Set(ManiaSetting.ScrollDirection, ManiaScrollingDirection.Up); } public override TrackedSettings CreateTrackedSettings() => new TrackedSettings { new TrackedSetting<double>(ManiaSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms")) }; } public enum ManiaSetting { ScrollTime, ScrollDirection } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Configuration.Tracking; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Configuration { public class ManiaConfigManager : RulesetConfigManager<ManiaSetting> { public ManiaConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null) : base(settings, ruleset, variant) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); Set(ManiaSetting.ScrollTime, 1500.0, 50.0, 10000.0, 50.0); Set(ManiaSetting.ScrollDirection, ManiaScrollingDirection.Down); } public override TrackedSettings CreateTrackedSettings() => new TrackedSettings { new TrackedSetting<double>(ManiaSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms")) }; } public enum ManiaSetting { ScrollTime, ScrollDirection } }
Fix problem when setting WebGL build to fullscreen
using UnityEngine; using System.Collections; public class CameraAspectAdjuster : MonoBehaviour { public Camera mainCamera; public float targetAspectRatio; // Use this for initialization void Awake () { float windowAspectRatio = (float)Screen.width / (float)Screen.height; float scale = windowAspectRatio / targetAspectRatio; // if scaled height is less than current height, add letterbox if (scale < 1.0f) { Rect rect = mainCamera.rect; rect.width = 1.0f; rect.height = scale; rect.x = 0; rect.y = (1.0f - scale) / 2.0f; mainCamera.rect = rect; } else if (scale > 1.0f) { // add pillarbox float scalewidth = 1.0f / scale; Rect rect = mainCamera.rect; rect.width = scalewidth; rect.height = 1.0f; rect.x = (1.0f - scalewidth) / 2.0f; rect.y = 0; mainCamera.rect = rect; } } }
using UnityEngine; using System.Collections; public class CameraAspectAdjuster : MonoBehaviour { public Camera mainCamera; public float targetAspectRatio; private float latestWindowAspectRatio; void Awake () { latestWindowAspectRatio = targetAspectRatio; AdjustIfNeeded (); } void Update () { AdjustIfNeeded (); } void AdjustIfNeeded () { float windowAspectRatio = (float)Screen.width / (float)Screen.height; if (windowAspectRatio != latestWindowAspectRatio) { float scale = windowAspectRatio / targetAspectRatio; // if scaled height is less than current height, add letterbox if (scale < 1.0f) { Rect rect = mainCamera.rect; rect.width = 1.0f; rect.height = scale; rect.x = 0; rect.y = (1.0f - scale) / 2.0f; mainCamera.rect = rect; } else if (scale > 1.0f) { // add pillarbox float scalewidth = 1.0f / scale; Rect rect = mainCamera.rect; rect.width = scalewidth; rect.height = 1.0f; rect.x = (1.0f - scalewidth) / 2.0f; rect.y = 0; mainCamera.rect = rect; } else { Rect rect = mainCamera.rect; rect.width = 1.0f; rect.height = 1.0f; rect.x = 0; rect.y = 0; mainCamera.rect = rect; } latestWindowAspectRatio = windowAspectRatio; } } }
Use TLS 1.2 for test suite
using System.Collections.Generic; namespace YouTrackSharp.Tests.Infrastructure { public class Connections { public static string ServerUrl => "https://ytsharp.myjetbrains.com/youtrack/"; public static Connection UnauthorizedConnection => new BearerTokenConnection(ServerUrl, "invalidtoken"); public static Connection Demo1Token => new BearerTokenConnection(ServerUrl, "perm:ZGVtbzE=.WW91VHJhY2tTaGFycA==.AX3uf8RYk3y2bupWA1xyd9BhAHoAxc"); public static Connection Demo2Token => new BearerTokenConnection(ServerUrl, "perm:ZGVtbzI=.WW91VHJhY2tTaGFycA==.GQEOl33LyTtmJvhWuz0Q629wbo8dk0"); public static Connection Demo3Token => new BearerTokenConnection(ServerUrl, "perm:ZGVtbzM=.WW91VHJhY2tTaGFycA==.L04RdcCnjyW2UPCVg1qyb6dQflpzFy"); public static class TestData { public static readonly List<object[]> ValidConnections = new List<object[]> { new object[] { Demo1Token }, new object[] { Demo2Token } }; public static readonly List<object[]> InvalidConnections = new List<object[]> { new object[] { UnauthorizedConnection } }; } } }
using System.Collections.Generic; using System.Net.Http; using System.Security.Authentication; namespace YouTrackSharp.Tests.Infrastructure { public class Connections { public static string ServerUrl => "https://ytsharp.myjetbrains.com/youtrack/"; public static Connection UnauthorizedConnection => new BearerTokenConnection(ServerUrl, "invalidtoken", handler => ConfigureTestsHandler(handler)); public static Connection Demo1Token => new BearerTokenConnection(ServerUrl, "perm:ZGVtbzE=.WW91VHJhY2tTaGFycA==.AX3uf8RYk3y2bupWA1xyd9BhAHoAxc", handler => ConfigureTestsHandler(handler)); public static Connection Demo2Token => new BearerTokenConnection(ServerUrl, "perm:ZGVtbzI=.WW91VHJhY2tTaGFycA==.GQEOl33LyTtmJvhWuz0Q629wbo8dk0", handler => ConfigureTestsHandler(handler)); public static Connection Demo3Token => new BearerTokenConnection(ServerUrl, "perm:ZGVtbzM=.WW91VHJhY2tTaGFycA==.L04RdcCnjyW2UPCVg1qyb6dQflpzFy", handler => ConfigureTestsHandler(handler)); public static class TestData { public static readonly List<object[]> ValidConnections = new List<object[]> { new object[] { Demo1Token }, new object[] { Demo2Token } }; public static readonly List<object[]> InvalidConnections = new List<object[]> { new object[] { UnauthorizedConnection } }; } private static void ConfigureTestsHandler(HttpClientHandler handler) { handler.SslProtocols = SslProtocols.Tls12; } } }
Revert back strategy for ImageSource - ApplicationBundle
using System; using Android.Graphics.Drawables; using System.IO; using FFImageLoading.Work; using Android.Content; using Android.Content.Res; using System.Threading.Tasks; namespace FFImageLoading { public class ApplicationBundleStreamResolver : IStreamResolver { private Context Context { get { return global::Android.App.Application.Context.ApplicationContext; } } public async Task<WithLoadingResult<Stream>> GetStream(string identifier) { var resourceId = Context.Resources.GetIdentifier (identifier.ToLower (), "drawable", Context.PackageName); Stream stream = null; if (resourceId != 0) { stream = Context.Resources.OpenRawResource (resourceId); } return WithLoadingResult.Encapsulate(stream, LoadingResult.ApplicationBundle); } public void Dispose() { } } }
using System; using Android.Graphics.Drawables; using System.IO; using FFImageLoading.Work; using Android.Content; using Android.Content.Res; using System.Threading.Tasks; namespace FFImageLoading { public class ApplicationBundleStreamResolver : IStreamResolver { private Context Context { get { return global::Android.App.Application.Context.ApplicationContext; } } public async Task<WithLoadingResult<Stream>> GetStream(string identifier) { return WithLoadingResult.Encapsulate(Context.Assets.Open(identifier, Access.Streaming), LoadingResult.ApplicationBundle); } public void Dispose() { } } }
Add company name to assembly.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Moxie")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Moxie")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("56cfcb5a-d997-4823-929c-d8bbf3027007")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Moxie")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ephox")] [assembly: AssemblyProduct("Moxie")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("56cfcb5a-d997-4823-929c-d8bbf3027007")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Rework resolvers DI registration (automatic)
using System; using Agiil.ObjectMaps; using Autofac; namespace Agiil.Bootstrap.ObjectMaps { public class AutomapperResolversModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<IdentityValueResolver>(); builder.RegisterGeneric(typeof(GetEntityByIdentityValueResolver<>)); builder.RegisterGeneric(typeof(GetEntityByIdentityResolver<>)); builder.RegisterGeneric(typeof(CreateIdentityResolver<>)); } } }
using System; using System.Collections.Generic; using System.Linq; using Agiil.ObjectMaps.Resolvers; using Autofac; namespace Agiil.Bootstrap.ObjectMaps { public class AutomapperResolversModule : Module { protected override void Load(ContainerBuilder builder) { var types = GetCandidateTypes(); foreach(var type in types) { if(type.IsGenericTypeDefinition) { builder.RegisterGeneric(type); } else { builder.RegisterType(type); } } } IEnumerable<Type> GetCandidateTypes() { var marker = typeof(IResolversNamespaceMarker); var searchNamespace = marker.Namespace; return (from type in marker.Assembly.GetExportedTypes() where type.Namespace.StartsWith(searchNamespace, StringComparison.InvariantCulture) && type.IsClass && !type.IsAbstract && type.IsAssignableTo<string>() select type); } } }
Move using directives outside of namespace
namespace FluentAssertions.Specs.Execution { using System.Collections.Generic; using FluentAssertions.Execution; internal class IgnoringFailuresAssertionStrategy : IAssertionStrategy { public IEnumerable<string> FailureMessages => new string[0]; public void HandleFailure(string message) { } public IEnumerable<string> DiscardFailures() => new string[0]; public void ThrowIfAny(IDictionary<string, object> context) { } } }
using System.Collections.Generic; using FluentAssertions.Execution; namespace FluentAssertions.Specs.Execution { internal class IgnoringFailuresAssertionStrategy : IAssertionStrategy { public IEnumerable<string> FailureMessages => new string[0]; public void HandleFailure(string message) { } public IEnumerable<string> DiscardFailures() => new string[0]; public void ThrowIfAny(IDictionary<string, object> context) { } } }
Set current directory to the executable directory, since windows services execute from system32.
using log4net; using spectator.Configuration; using spectator.Metrics; using spectator.Sources; using StatsdClient; using Topshelf; namespace spectator { public class Program { private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public static void Main(string[] args) { var configurationResolver = new ConfigurationResolver(); Log.Info("Starting spectator topshelf host"); HostFactory.Run(hostConfigurator => { hostConfigurator.Service<SpectatorService>(serviceConfigurator => { var configuration = configurationResolver.Resolve(); serviceConfigurator.ConstructUsing(() => new SpectatorService( configuration, new QueryableSourceFactory(), new StatsdPublisher( new Statsd( new StatsdUDP( configuration.StatsdHost, configuration.StatsdPort ) ) ), new MetricFormatter() ) ); serviceConfigurator.WhenStarted(myService => myService.Start()); serviceConfigurator.WhenStopped(myService => myService.Stop()); }); hostConfigurator.RunAsLocalSystem(); hostConfigurator.SetDisplayName(@"Spectator Agent"); hostConfigurator.SetDescription(@"Monitors system metrics and sends them to a statsd-compatible server."); hostConfigurator.SetServiceName(@"Spectator"); }); } } }
using log4net; using spectator.Configuration; using spectator.Metrics; using spectator.Sources; using StatsdClient; using Topshelf; namespace spectator { public class Program { private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public static void Main(string[] args) { System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); var configurationResolver = new ConfigurationResolver(); Log.Info("Starting spectator topshelf host"); HostFactory.Run(hostConfigurator => { hostConfigurator.Service<SpectatorService>(serviceConfigurator => { var configuration = configurationResolver.Resolve(); serviceConfigurator.ConstructUsing(() => new SpectatorService( configuration, new QueryableSourceFactory(), new StatsdPublisher( new Statsd( new StatsdUDP( configuration.StatsdHost, configuration.StatsdPort ) ) ), new MetricFormatter() ) ); serviceConfigurator.WhenStarted(myService => myService.Start()); serviceConfigurator.WhenStopped(myService => myService.Stop()); }); hostConfigurator.RunAsLocalSystem(); hostConfigurator.SetDisplayName(@"Spectator Agent"); hostConfigurator.SetDescription(@"Monitors system metrics and sends them to a statsd-compatible server."); hostConfigurator.SetServiceName(@"Spectator"); }); } } }
Add curly braces around the nested statement in if block
using AVKit; namespace MediaManager.Platforms.Ios.Video { public class PlayerViewController : AVPlayerViewController { protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple; public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (MediaManager.MediaPlayer.VideoView == View.Superview) MediaManager.MediaPlayer.VideoView = null; Player = null; } } }
using AVKit; namespace MediaManager.Platforms.Ios.Video { public class PlayerViewController : AVPlayerViewController { protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple; public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (MediaManager.MediaPlayer.VideoView == View.Superview) { MediaManager.MediaPlayer.VideoView = null; } Player = null; } } }
Add Serialization test category to aid CI configuration.
using Duplicati.Library.Modules.Builtin; using Duplicati.Library.Modules.Builtin.ResultSerialization; using NUnit.Framework; namespace Duplicati.UnitTest { [TestFixture] public class ResultFormatSerializerProviderTest { [Test] public void TestGetSerializerGivenDuplicatiReturnsDuplicatiSerializer() { IResultFormatSerializer serializer = ResultFormatSerializerProvider.GetSerializer(ResultExportFormat.Duplicati); Assert.AreEqual(typeof(DuplicatiFormatSerializer), serializer.GetType()); } [Test] public void TestGetSerializerGivenJsonReturnsJsonSerializer() { IResultFormatSerializer serializer = ResultFormatSerializerProvider.GetSerializer(ResultExportFormat.Json); Assert.AreEqual(typeof(JsonFormatSerializer), serializer.GetType()); } } }
using Duplicati.Library.Modules.Builtin; using Duplicati.Library.Modules.Builtin.ResultSerialization; using NUnit.Framework; namespace Duplicati.UnitTest { [TestFixture] public class ResultFormatSerializerProviderTest { [Test] [Category("Serialization")] public void TestGetSerializerGivenDuplicatiReturnsDuplicatiSerializer() { IResultFormatSerializer serializer = ResultFormatSerializerProvider.GetSerializer(ResultExportFormat.Duplicati); Assert.AreEqual(typeof(DuplicatiFormatSerializer), serializer.GetType()); } [Test] [Category("Serialization")] public void TestGetSerializerGivenJsonReturnsJsonSerializer() { IResultFormatSerializer serializer = ResultFormatSerializerProvider.GetSerializer(ResultExportFormat.Json); Assert.AreEqual(typeof(JsonFormatSerializer), serializer.GetType()); } } }
Detach VideoView on disappearing (iOS)
using AVKit; namespace MediaManager.Platforms.Ios.Video { public class PlayerViewController : AVPlayerViewController { public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); Player = null; } } }
using AVKit; namespace MediaManager.Platforms.Ios.Video { public class PlayerViewController : AVPlayerViewController { protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple; public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (MediaManager.MediaPlayer.VideoView == View.Superview) MediaManager.MediaPlayer.VideoView = null; Player = null; } } }
Remove editorbrowsable attribute from Configure
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Internal { using System; using System.ComponentModel; /// <summary> /// Represents an object that is configurable. /// </summary> /// <typeparam name="TConfiguration">Type of object being configured</typeparam> /// <typeparam name="TNext">Return type</typeparam> public interface IConfigurable<TConfiguration, out TNext> { /// <summary> /// Configures the current object. /// </summary> /// <param name="configurator">Action to configure the object.</param> /// <returns></returns> [EditorBrowsable(EditorBrowsableState.Never)] TNext Configure(Action<TConfiguration> configurator); } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Internal { using System; using System.ComponentModel; /// <summary> /// Represents an object that is configurable. /// </summary> /// <typeparam name="TConfiguration">Type of object being configured</typeparam> /// <typeparam name="TNext">Return type</typeparam> public interface IConfigurable<TConfiguration, out TNext> { /// <summary> /// Configures the current object. /// </summary> /// <param name="configurator">Action to configure the object.</param> /// <returns></returns> TNext Configure(Action<TConfiguration> configurator); } }
Copy basic Boogie parser stuff from Adam's DynamicAnalysis tool. Things are still broken. The type checker throws an exception when trying to resolve()
using System; using Microsoft; using System.Linq; using Microsoft.Boogie; using System.Diagnostics; namespace symbooglix { public class driver { public static int Main(String[] args) { if (args.Length == 0) { Console.WriteLine ("Pass boogie file as first arg!"); return 1; } Debug.Listeners.Add(new TextWriterTraceListener(Console.Error)); //Microsoft.Boogie.Program p = null; Program p = null; System.Collections.Generic.List<string> defines = null; int success = Parser.Parse (args[0], defines, out p); if (success != 0) { Console.WriteLine("Failed to parse"); return 1; } IStateScheduler scheduler = new DFSStateScheduler(); PrintingExecutor e = new PrintingExecutor(p, scheduler); // FIXME: Find a better way to choose entry point. Microsoft.Boogie.Implementation entry = p.TopLevelDeclarations.OfType<Implementation>().FirstOrDefault(); return e.run(entry)? 1 : 0; } } }
using System; using Microsoft; using System.Linq; using Microsoft.Boogie; using System.Diagnostics; using System.Collections.Generic; namespace symbooglix { public class driver { public static int Main(String[] args) { if (args.Length == 0) { Console.WriteLine ("Pass boogie file as first arg!"); return 1; } Debug.Listeners.Add(new TextWriterTraceListener(Console.Error)); Program p = null; var defines = new List<String> { "FILE_0" }; // WTF?? int errors = Parser.Parse (args[0], defines, out p); if (errors != 0) { Console.WriteLine("Failed to parse"); return 1; } errors = p.Resolve(); if (errors != 0) { Console.WriteLine("Failed to resolve."); return 1; } errors = p.Typecheck(); if (errors != 0) { Console.WriteLine("Failed to resolve."); return 1; } IStateScheduler scheduler = new DFSStateScheduler(); PrintingExecutor e = new PrintingExecutor(p, scheduler); // FIXME: Find a better way to choose entry point. Microsoft.Boogie.Implementation entry = p.TopLevelDeclarations.OfType<Implementation>().FirstOrDefault(); return e.run(entry)? 1 : 0; } } }
Add json ignor to brave
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Dapper.FastCrud; using Smooth.IoC.Cqrs.Query; using Smooth.IoC.Cqrs.Requests; namespace Rik.Codecamp.Entities { public class Brave : IRequest, IQuery { [Key, DatabaseGeneratedDefaultValue] public int Id { get; set; } [ForeignKey("New")] public int NewId { get; set; } public New New { get; set; } [ForeignKey("World")] public int WorldId { get; set; } public World World { get; set; } [NotMapped] public int Version { get; } = 0; [NotMapped] public Guid QueryId { get; } = Guid.NewGuid(); [NotMapped] public Guid RequestId { get; } = Guid.NewGuid(); } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Dapper.FastCrud; using Newtonsoft.Json; using Smooth.IoC.Cqrs.Query; using Smooth.IoC.Cqrs.Requests; namespace Rik.Codecamp.Entities { public class Brave : IRequest, IQuery { [Key, DatabaseGeneratedDefaultValue] public int Id { get; set; } [ForeignKey("New")] public int NewId { get; set; } public New New { get; set; } [ForeignKey("World")] public int WorldId { get; set; } public World World { get; set; } [NotMapped, JsonIgnore] public int Version { get; } = 0; [NotMapped, JsonIgnore] public Guid QueryId { get; } = Guid.NewGuid(); [NotMapped, JsonIgnore] public Guid RequestId { get; } = Guid.NewGuid(); } }
Add link to PDF Download to make it more discoverable
@{ ViewBag.Title = "Home Page"; } <h2>Demo Start Page</h2>
@{ ViewBag.Title = "Home Page"; } <h2>Demo Start Page</h2> @Html.ActionLink("Download PDF","ContributorsList")
Fix typo that don't compile.
// // ReadRegisters.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; namespace NitroDebugger.RSP.Packets { public class ReadRegisters : CommandPacket { public ReadRegisters() : base('g') { } protected override string PackArguments() { return ""; } } }
// // ReadRegisters.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; namespace NitroDebugger.RSP.Packets { public class ReadRegisters : CommandPacket { public ReadRegisters() : base("g") { } protected override string PackArguments() { return ""; } } }
Revert "Change levy run date to 24th"
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 10 24 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 15 20 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }
Add notes editing only when over auxiliary line
using UnityEngine; public class NoteObject : MonoBehaviour { public NotePosition notePosition; public int noteType; NotesEditorModel model; RectTransform rectTransform; void Awake() { model = NotesEditorModel.Instance; rectTransform = GetComponent<RectTransform>(); rectTransform.localPosition = CalcPosition(notePosition); } void LateUpdate() { rectTransform.localPosition = CalcPosition(notePosition); } Vector3 CalcPosition(NotePosition notePosition) { return new Vector3( model.SamplesToScreenPositionX(notePosition.samples), model.BlockNumToScreenPositionY(notePosition.blockNum) * model.CanvasScaleFactor.Value, 0); } public void OnMouseEnter() { model.IsMouseOverCanvas.Value = true; } public void OnMouseDown() { model.NormalNoteObservable.OnNext(notePosition); } }
using UnityEngine; public class NoteObject : MonoBehaviour { public NotePosition notePosition; public int noteType; NotesEditorModel model; RectTransform rectTransform; void Awake() { model = NotesEditorModel.Instance; rectTransform = GetComponent<RectTransform>(); rectTransform.localPosition = CalcPosition(notePosition); } void LateUpdate() { rectTransform.localPosition = CalcPosition(notePosition); } Vector3 CalcPosition(NotePosition notePosition) { return new Vector3( model.SamplesToScreenPositionX(notePosition.samples), model.BlockNumToScreenPositionY(notePosition.blockNum) * model.CanvasScaleFactor.Value, 0); } public void OnMouseEnter() { model.IsMouseOverCanvas.Value = true; } public void OnMouseDown() { if (model.ClosestNotePosition.Value.Equals(notePosition)) { model.NormalNoteObservable.OnNext(notePosition); } } }
Fix for duplicate type in assembly error
using System; using System.Collections.Generic; using Microsoft.Extensions.DiagnosticAdapter.Internal; namespace Glimpse.Agent.Internal.Inspectors.Mvc.Proxies { public class ProxyAdapter { private static readonly ProxyTypeCache _cache = new ProxyTypeCache(); public ProxyAdapter() { Listener = new Dictionary<string, Subscription>(); } private IDictionary<string, Subscription> Listener { get; } public void Register(string typeName) { var subscription = new Subscription(); Listener.Add(typeName, subscription); } public T Process<T>(string typeName, object target) { Subscription subscription; if (!Listener.TryGetValue(typeName, out subscription)) { return default(T); } if (subscription.ProxiedType == null) { var proxiedType = ProxyTypeEmitter.GetProxyType(_cache, typeof(T), target.GetType()); subscription.ProxiedType = proxiedType; } var instance = (T)Activator.CreateInstance(subscription.ProxiedType, target); return instance; } private class Subscription { public Type ProxiedType { get; set; } } } }
using System; using System.Collections.Generic; using Microsoft.Extensions.DiagnosticAdapter.Internal; namespace Glimpse.Agent.Internal.Inspectors.Mvc.Proxies { public class ProxyAdapter { private static readonly ProxyTypeCache _cache = new ProxyTypeCache(); public ProxyAdapter() { Listener = new Dictionary<string, Subscription>(); } private IDictionary<string, Subscription> Listener { get; } public void Register(string typeName) { var subscription = new Subscription(); Listener.Add(typeName, subscription); } public T Process<T>(string typeName, object target) { Subscription subscription; if (!Listener.TryGetValue(typeName, out subscription)) { return default(T); } if (subscription.ProxiedType == null) { lock (subscription) { if (subscription.ProxiedType == null) { var proxiedType = ProxyTypeEmitter.GetProxyType(_cache, typeof(T), target.GetType()); subscription.ProxiedType = proxiedType; } } } var instance = (T)Activator.CreateInstance(subscription.ProxiedType, target); return instance; } private class Subscription { public Type ProxiedType { get; set; } } } }
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.1.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.Attributed 3.1.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.1.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.Attributed 3.1.0")]
Improve MultiMiner Remoting compatibility on Linux+Mono
using System; using System.ServiceModel; namespace MultiMiner.Remoting.Server { public class RemotingServer { private bool serviceStarted = false; private ServiceHost myServiceHost = null; public void Startup() { Uri baseAddress = new Uri("net.tcp://localhost:" + Config.RemotingPort + "/RemotingService"); NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); myServiceHost = new ServiceHost(typeof(RemotingService), baseAddress); myServiceHost.AddServiceEndpoint(typeof(IRemotingService), binding, baseAddress); myServiceHost.Open(); serviceStarted = true; } public void Shutdown() { if (!serviceStarted) return; myServiceHost.Close(); myServiceHost = null; serviceStarted = false; } } }
using System; using System.Net; using System.ServiceModel; namespace MultiMiner.Remoting.Server { public class RemotingServer { private bool serviceStarted = false; private ServiceHost myServiceHost = null; public void Startup() { //use Dns.GetHostName() instead of localhost for compatibility with Mono+Linux //https://github.com/nwoolls/MultiMiner/issues/62 Uri baseAddress = new Uri(String.Format("net.tcp://{0}:{1}/RemotingService", Dns.GetHostName(), Config.RemotingPort)); NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); myServiceHost = new ServiceHost(typeof(RemotingService), baseAddress); myServiceHost.AddServiceEndpoint(typeof(IRemotingService), binding, baseAddress); myServiceHost.Open(); serviceStarted = true; } public void Shutdown() { if (!serviceStarted) return; myServiceHost.Close(); myServiceHost = null; serviceStarted = false; } } }
Add null check to cache refresher
using Autofac; using Newtonsoft.Json; using System; using System.Collections.Concurrent; using TeaCommerce.Api.Dependency; using TeaCommerce.Api.Infrastructure.Caching; using umbraco.interfaces; using Umbraco.Core.Cache; namespace TeaCommerce.Umbraco.Application.Caching { public abstract class TeaCommerceCacheRefresherBase<TInstanceType, TEntity, TId> : JsonCacheRefresherBase<TInstanceType> where TInstanceType : ICacheRefresher { protected ICacheService CacheService => DependencyContainer.Instance.Resolve<ICacheService>(); public abstract string CacheKeyFormat { get; } public override void Refresh(string jsonPayload) { var payload = JsonConvert.DeserializeObject<TeaCommerceCacheRefresherPayload<TId>>(jsonPayload); // Make sure it wasn't this instance that sent the payload if (payload.InstanceId != Constants.InstanceId) { var cacheKey = string.Format(CacheKeyFormat, payload.StoreId, payload.Id); var cache = CacheService.GetCacheValue<ConcurrentDictionary<TId, TEntity>>(cacheKey); if (cache.ContainsKey(payload.Id)) { cache.TryRemove(payload.Id, out var removed); } base.Refresh(jsonPayload); } } public override void Refresh(int id) { throw new NotSupportedException(); } public override void Refresh(Guid id) { throw new NotSupportedException(); } public override void RefreshAll() { throw new NotSupportedException(); } public override void Remove(int id) { throw new NotSupportedException(); } } }
using Autofac; using Newtonsoft.Json; using System; using System.Collections.Concurrent; using TeaCommerce.Api.Dependency; using TeaCommerce.Api.Infrastructure.Caching; using umbraco.interfaces; using Umbraco.Core.Cache; namespace TeaCommerce.Umbraco.Application.Caching { public abstract class TeaCommerceCacheRefresherBase<TInstanceType, TEntity, TId> : JsonCacheRefresherBase<TInstanceType> where TInstanceType : ICacheRefresher { protected ICacheService CacheService => DependencyContainer.Instance.Resolve<ICacheService>(); public abstract string CacheKeyFormat { get; } public override void Refresh(string jsonPayload) { var payload = JsonConvert.DeserializeObject<TeaCommerceCacheRefresherPayload<TId>>(jsonPayload); // Make sure it wasn't this instance that sent the payload if (payload != null && payload.InstanceId != Constants.InstanceId) { var cacheKey = string.Format(CacheKeyFormat, payload.StoreId, payload.Id); var cache = CacheService.GetCacheValue<ConcurrentDictionary<TId, TEntity>>(cacheKey); if (cache != null && cache.ContainsKey(payload.Id)) { cache.TryRemove(payload.Id, out var removed); } base.Refresh(jsonPayload); } } public override void Refresh(int id) { throw new NotSupportedException(); } public override void Refresh(Guid id) { throw new NotSupportedException(); } public override void RefreshAll() { throw new NotSupportedException(); } public override void Remove(int id) { throw new NotSupportedException(); } } }
Create an empty Home controller.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Tigwi.UI.Controllers { public class HomeController : Controller { public ActionResult Index() { throw new NotImplementedException("HomeController.Index"); } public ActionResult About() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Tigwi.UI.Controllers { public class HomeController : Controller { public ActionResult Index() { this.ViewBag.CurrentUser = "Zak"; return this.View(); } public ActionResult About() { return View(); } } }
Remove unnecessary object creation of IAnnotation
using System.Net; using Criteo.Profiling.Tracing.Annotation; namespace Criteo.Profiling.Tracing { /// <summary> /// Factory for annotations /// </summary> public static class Annotations { public static IAnnotation ClientRecv() { return new ClientRecv(); } public static IAnnotation ClientSend() { return new ClientSend(); } public static IAnnotation ServerRecv() { return new ServerRecv(); } public static IAnnotation ServerSend() { return new ServerSend(); } public static IAnnotation Rpc(string name) { return new Rpc(name); } public static IAnnotation ServiceName(string name) { return new ServiceName(name); } public static IAnnotation LocalAddr(IPEndPoint endPoint) { return new LocalAddr(endPoint); } public static IAnnotation Binary(string key, object value) { return new BinaryAnnotation(key, value); } public static IAnnotation Event(string name) { return new Event(name); } } }
using System.Net; using Criteo.Profiling.Tracing.Annotation; namespace Criteo.Profiling.Tracing { /// <summary> /// Factory for annotations /// </summary> public static class Annotations { private static readonly IAnnotation AnnClientReceive = new ClientRecv(); private static readonly IAnnotation AnnClientSend = new ClientSend(); private static readonly IAnnotation AnnServerReceive = new ServerRecv(); private static readonly IAnnotation AnnServerSend = new ServerSend(); public static IAnnotation ClientRecv() { return AnnClientReceive; } public static IAnnotation ClientSend() { return AnnClientSend; } public static IAnnotation ServerRecv() { return AnnServerReceive; } public static IAnnotation ServerSend() { return AnnServerSend; } public static IAnnotation Rpc(string name) { return new Rpc(name); } public static IAnnotation ServiceName(string name) { return new ServiceName(name); } public static IAnnotation LocalAddr(IPEndPoint endPoint) { return new LocalAddr(endPoint); } public static IAnnotation Binary(string key, object value) { return new BinaryAnnotation(key, value); } public static IAnnotation Event(string name) { return new Event(name); } } }
Allow base master page to be overridden
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.UI.WebControls; using System.Reflection; using System.Web.UI; namespace CodeTorch.Web.MasterPages { public class BaseMasterPage : System.Web.UI.MasterPage { protected Label currentYear; protected Label currentAppVersion; protected Label copyrightCompanyName; protected void Page_Load(object sender, EventArgs e) { if (currentYear != null) this.currentYear.Text = DateTime.Now.Year.ToString(); if (currentAppVersion != null) this.currentAppVersion.Text = GetCurrentVersion(); if (copyrightCompanyName != null) this.copyrightCompanyName.Text = CodeTorch.Core.Configuration.GetInstance().App.CopyrightCompanyName; } protected string GetCurrentVersion() { Assembly currentAssembly = Assembly.GetExecutingAssembly(); Version appVersion = currentAssembly.GetName().Version; return string.Format("{0}.{1}.{2}", appVersion.Major.ToString(), appVersion.Minor.ToString(), appVersion.Build.ToString()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.UI.WebControls; using System.Reflection; using System.Web.UI; namespace CodeTorch.Web.MasterPages { public class BaseMasterPage : System.Web.UI.MasterPage { protected Label currentYear; protected Label currentAppVersion; protected Label copyrightCompanyName; protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (currentYear != null) this.currentYear.Text = DateTime.Now.Year.ToString(); if (currentAppVersion != null) this.currentAppVersion.Text = GetCurrentVersion(); if (copyrightCompanyName != null) this.copyrightCompanyName.Text = CodeTorch.Core.Configuration.GetInstance().App.CopyrightCompanyName; } protected string GetCurrentVersion() { Assembly currentAssembly = Assembly.GetExecutingAssembly(); Version appVersion = currentAssembly.GetName().Version; return string.Format("{0}.{1}.{2}", appVersion.Major.ToString(), appVersion.Minor.ToString(), appVersion.Build.ToString()); } } }
Add a unified method to make an editor-only object
using UnityEditor; using UnityEditor.SceneManagement; namespace YesAndEditor { // Static class packed to the brim with helpful Unity editor utilities. public static class YesAndEditorUtil { // Forcefully mark open loaded scenes dirty and save them. [MenuItem ("File/Force Save")] public static void ForceSaveOpenScenes () { EditorSceneManager.MarkAllScenesDirty (); EditorSceneManager.SaveOpenScenes (); } } }
using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using System.Linq; namespace YesAndEditor { // Static class packed to the brim with helpful Unity editor utilities. public static class YesAndEditorUtil { // Forcefully mark open loaded scenes dirty and save them. [MenuItem ("File/Force Save")] public static void ForceSaveOpenScenes () { EditorSceneManager.MarkAllScenesDirty (); EditorSceneManager.SaveOpenScenes (); } // Mark an object editor-only. public static void SetEditorOnly(this MonoBehaviour obj, bool editorOnly = true) { if (editorOnly) { obj.gameObject.hideFlags ^= HideFlags.NotEditable; obj.gameObject.hideFlags ^= HideFlags.HideAndDontSave; } else { obj.gameObject.hideFlags &= HideFlags.NotEditable; obj.gameObject.hideFlags &= HideFlags.HideAndDontSave; } } } }
Remove 100sec boot screen =D
using System; using System.Threading.Tasks; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace FridgeShoppingList.Views { public sealed partial class Splash : UserControl { public Task SplashInProgress { get; private set; } public Splash(SplashScreen splashScreen) { InitializeComponent(); Window.Current.SizeChanged += (s, e) => Resize(splashScreen); Resize(splashScreen); SplashInProgress = BeginSplashProcess(); } private async Task BeginSplashProcess() { await Task.Delay(100000); } private void Resize(SplashScreen splashScreen) { TextTransform.TranslateY = splashScreen.ImageLocation.Height * .75; } private void Image_Loaded(object sender, RoutedEventArgs e) { StarfleetRotateStoryboard.Begin(); } } }
using System; using System.Threading.Tasks; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace FridgeShoppingList.Views { public sealed partial class Splash : UserControl { public Task SplashInProgress { get; private set; } public Splash(SplashScreen splashScreen) { InitializeComponent(); Window.Current.SizeChanged += (s, e) => Resize(splashScreen); Resize(splashScreen); SplashInProgress = BeginSplashProcess(); } private async Task BeginSplashProcess() { //Simulate some kind of fun login text here await Task.Delay(10000); } private void Resize(SplashScreen splashScreen) { TextTransform.TranslateY = splashScreen.ImageLocation.Height * .75; } private void Image_Loaded(object sender, RoutedEventArgs e) { StarfleetRotateStoryboard.Begin(); } } }
Rename variable in Automapper config to match its type (Job instead of JobDTO)
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- // This file reused from: https://code.msdn.microsoft.com/Field-Engineer-501df99d using AutoMapper; using FieldEngineerLite.Service.DataObjects; using FieldEngineerLite.Service.Models; namespace FieldEngineerLite.Service { public class AutomapperConfiguration { public static void CreateMapping(IConfiguration cfg) { // Apply some name changes from the entity to the DTO cfg.CreateMap<Job, JobDTO>() .ForMember(jobDTO => jobDTO.Equipments, map => map.MapFrom(job => job.Equipments)); // For incoming requests, ignore the relationships cfg.CreateMap<JobDTO, Job>() .ForMember(jobDTO => jobDTO.Customer, map => map.Ignore()) .ForMember(jobDTO => jobDTO.Equipments, map => map.Ignore()); cfg.CreateMap<Customer, CustomerDTO>(); cfg.CreateMap<Equipment, EquipmentDTO>(); } } }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- // This file reused from: https://code.msdn.microsoft.com/Field-Engineer-501df99d using AutoMapper; using FieldEngineerLite.Service.DataObjects; using FieldEngineerLite.Service.Models; namespace FieldEngineerLite.Service { public class AutomapperConfiguration { public static void CreateMapping(IConfiguration cfg) { // Apply some name changes from the entity to the DTO cfg.CreateMap<Job, JobDTO>() .ForMember(jobDTO => jobDTO.Equipments, map => map.MapFrom(job => job.Equipments)); // For incoming requests, ignore the relationships cfg.CreateMap<JobDTO, Job>() .ForMember(job => job.Customer, map => map.Ignore()) .ForMember(job => job.Equipments, map => map.Ignore()); cfg.CreateMap<Customer, CustomerDTO>(); cfg.CreateMap<Equipment, EquipmentDTO>(); } } }
Update todo message to explain what is the issue
using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Glimpse.Web; using System; namespace Glimpse.Host.Web.AspNet { public class GlimpseMiddleware { private readonly RequestDelegate _innerNext; private readonly MasterRequestRuntime _runtime; private readonly ISettings _settings; private readonly IContextData<MessageContext> _contextData; public GlimpseMiddleware(RequestDelegate innerNext, IServiceProvider serviceProvider) { _innerNext = innerNext; _runtime = new MasterRequestRuntime(serviceProvider); _contextData = new ContextData<MessageContext>(); } public async Task Invoke(Microsoft.AspNet.Http.HttpContext context) { var newContext = new HttpContext(context, _settings); // TODO: This is the wrong place for this, AgentRuntime isn't garenteed to execute first _contextData.Value = new MessageContext { Id = Guid.NewGuid(), Type = "Request" }; await _runtime.Begin(newContext); var handler = (IRequestHandler)null; if (_runtime.TryGetHandle(newContext, out handler)) { await handler.Handle(newContext); } else { await _innerNext(context); } // TODO: This doesn't work correctly :( await _runtime.End(newContext); } } }
using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Glimpse.Web; using System; namespace Glimpse.Host.Web.AspNet { public class GlimpseMiddleware { private readonly RequestDelegate _innerNext; private readonly MasterRequestRuntime _runtime; private readonly ISettings _settings; private readonly IContextData<MessageContext> _contextData; public GlimpseMiddleware(RequestDelegate innerNext, IServiceProvider serviceProvider) { _innerNext = innerNext; _runtime = new MasterRequestRuntime(serviceProvider); _contextData = new ContextData<MessageContext>(); } public async Task Invoke(Microsoft.AspNet.Http.HttpContext context) { var newContext = new HttpContext(context, _settings); // TODO: This is the wrong place for this, AgentRuntime isn't garenteed to execute first _contextData.Value = new MessageContext { Id = Guid.NewGuid(), Type = "Request" }; await _runtime.Begin(newContext); var handler = (IRequestHandler)null; if (_runtime.TryGetHandle(newContext, out handler)) { await handler.Handle(newContext); } else { await _innerNext(context); } // TODO: This doesn't work correctly :( (headers) await _runtime.End(newContext); } } }